JavaScript 小技巧

1.sleep 延迟函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
function sleep(delay) {
var start = new Date().getTime();
while (new Date().getTime() - start < delay) {
continue;
}
}

function test() {
console.log("111");
sleep(2000);
console.log("222");
}

test();

2.获取 URL 参数

1
2
3
4
decodeURI("%E5%95%8A%E5%93%88%E5%93%88"); // 解码中文
// window.location.search 获取 URL 参数
let params = new URLSearchParams("?project=js&type=1").get("type");
console.log(params);

3.判断简化

1
2
3
4
5
6
7
8
9
let a = 1;

if (a == 1 || a == 2) {
console.log(a);
}

if ([1, 2].includes(a)) {
console.log(a);
}

4.清空数组

1
2
3
let array = ["A", "B", "C", "D", "E", "F"];
array.length = 0;
console.log(array); // []

5.计算代码性能

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// web Api
const startTime = performance.now();
// 某些程序
for (let i = 0; i < 1000; i++) {
console.log(i);
}
const endTime = performance.now();
const totaltime = endTime - startTime;
console.log(totaltime); // 16.5
/* ------------------------------------------- */
const startTime = new Date().getTime();
// 某些程序
for (let i = 0; i < 1000; i++) {
console.log(i);
}
const endTime = new Date().getTime();
const totaltime = endTime - startTime;
console.log(totaltime); // 16.5

6.拼接数组

1
2
3
4
5
6
7
8
let a = [1, 2, 3];
let b = [4, 5, 6];
let 合并数组1 = a.concat(b); // [ 1, 2, 3, 4, 5, 6 ]
let 合并数组2 = [...a, ...b]; // [ 1, 2, 3, 4, 5, 6 ]

// 但是使用concat()方法时,如果需要合并的数组很大,那么concat() 函数会在创建单独的新数组时消耗大量内存。这时可以使用以下方法来实现数组的合并:
Array.prototype.push.apply(a, b);
console.log(a);

7.判断 null 和 undefined

1
2
3
4
5
6
7
8
9
let a;
if (a == null || a == undefined) {
console.log("a is null or undefined");
}
console.log(`-------------------`);
let b = undefined;
// 空值合并操作符
a ?? console.log("a is null or undefined");
b ?? console.log("b is null or undefined");

8.伪数组转为数组

1
2
3
Array.prototype.slice.call(arguments);
// or
[...arguments];

9.对象动态声明属性

1
2
3
4
5
6
7
const dynamic = "color";
var item = {
brand: "Ford",
[dynamic]: "Blue",
};
console.log(item);
// { brand: "Ford", color: "Blue" }

10.缩短 console.log()

1
2
3
4
// Web Api
const c = console.log.bind(document);
c(996);
c("hello world");

11.检查对象是否为空

1
2
Object.keys({}).length; // 0
Object.keys({ key: 1 }).length; // 1