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});

转载于:https://www.cnblogs.com/mengff/p/4770163.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值