JavaScript小技巧(1)
Author: Vic.Wang 2017/04/27
分享一些JavaScript小技巧,可以用来装逼装深沉哟!
1、数值边界判断简化
//判断 index 是否小于0,小于则赋值为 0
var index = 0;
//简化前
index--;
if (index < 0) {
index = 0;
}
//简化后
index = Math.max(0, --index);
//判断 index 是否大于 len,大于则赋值为 len 的值
var imgs = [1, 2, 3];
var index = 0,
len = imgs.length;
//简化前
index++;
if (index > len) {
index = len;
}
//简化后
index = Math.min(len, ++index);
2、JS对象深拷贝
newObj = JSON.parse(JSON.stringify(obj));
3、运行耗时计时
console.time('Timer'); //Timer是计时器名称,随便起
var arr = [];
for (var i = 0; i < 50; i++) {
arr.push(i);
}
console.timeEnd('Timer');
4、取随机字符串
Math.random().toString(16).substring(2) // 13位
Math.random().toString(36).substring(2) // 11位
5、匿名函数自执行
( function() {}() );
( function() {} )();
[ function() {}() ];
~ function() {}();
! function() {}();
+ function() {}();
- function() {}();
delete function() {}();
typeof function() {}();
void function() {}();
new function() {}();
new function() {};
var f = function() {}();
1, function() {}();
1 ^ function() {}();
1 > function() {}();
6、取整
~~2.33; //2
2.33 | 0; //2
2.33 >> 0; //2
7、两个整数交换数值
var a = 1, b = 2;
a ^= b;
b ^= a;
a -= b;
8、数组去重
[...new Set([1, "1", 2, 1, 1, 3])]; //[1, "1", 2, 3]
9、取出一个数组中的最大值和最小值
var numbers = [5, 458 , 120 , -215 , 228 , 400 , 122205, -85411];
Math.max.apply(Math, numbers); //122205
Math.min.apply(Math, numbers); //-85411
本文地址:http://blog.mingsixue.com/it/JS-technique-1.html
文章若需转载,请附上原文链接,谢谢配合。^_^