JavaScript 技巧总结

日期
1. 日期时间戳
+new Date() = new Date().getTime()

数组
1. 类数组转数组
var arr = Array.prototype.slice.call(arguments)

2. 连接类数组
Array.prototype.push.apply(arr, arguments)

3. 数组插入另一个数组的指定位置
var a = [1,2,3,7,8,9];
var b = [4,5,6];
var insertIndex = 3;
a.splice.apply(a, Array.prototype.concat(insertIndex, 0, b));

4. 数组最大值和最小值
Math.max.apply(Math,[1,2,3])
Math.max.apply(Math,[1,2,3])

5. 截断数组和清空数组
var arr = [1, 2, 3];
arr.length = 1;
console.log(arr); // [1]
arr.length = 0;
console.log(arr); // []
arr.length = 5;
console.log(arr); // [1,2,3,undefined,undefined]

6. 数组深复制
var a = [1, 2, 3];
var b = a.concat(); // a的深复制

7. 数组元素删除
数组元素删除使用 splice,不能使用delete,delete只是将元素置为undefined
对象属性删除 delete

8.其他

获取数组末尾的m个元素  Array.prototype.slice(-m)
数组截断   array.length = m (m < array.length)
数组洗牌   array.sort(function(){Math.random - 0.5 })

字符串
1. 去除首尾空格
String.prototype.trim = function(){return this.replace(/^\s+|\s+$/g, "");}

2. 使用+将字符串转换成数字

+'123' = 123

随机数
1. 从数组中随机获取成员
var items = [12, 548 , 'a' , 2 , 5478 , 'foo' , 8852, , 'Doe' , 2145 , 119];
var randomItem = items[Math.floor(Math.random() * items.length)];

2. 获取指定范围的随机数
var x = Math.floor(Math.random() * (max - min + 1)) + min;

3. 生成随机码
Math.random().toString(16).substring(2);
Math.random().toString(36).substring(2);

4. 生成随机的字母和数字组成的字符串
function generateRandomAlphaNum(len) {
var rdmString = "";
for( ; rdmString.length < len; rdmString += Math.random().toString(36).substr(2));
return rdmString.substr(0, len);
}

5. 对数字数组进行随机排序
var numbers = [5, 458 , 120 , -215 , 228 , 400 , 122205, -85411];
numbers = numbers.sort(function(){ return Math.random() - 0.5});

posted @ 2015-08-30 00:10  全玉  阅读(156)  评论(0编辑  收藏  举报