随机字符串
Math.random().toString(16).substring(2)
3、if比较
["toString"]() === "100"
取整
var a= 2.33 | 0
数组去重
[...new Set([1, "1", 2, 1, 1, 3])]
实现一个长度为m(3)且值都n(8)的数组
Array(3).fill(8)
取出一个数组中的最大值和最小值
var numbers = [5, 458 , 120 , -215 , 228 , 400 , 122205, -85411];
var maxInNumbers = Math.max.apply(Math, numbers);
var minInNumbers = Math.min.apply(Math, numbers);
console.log(maxInNumbers,minInNumbers);
判断奇偶数
对一个数字 &1可以判断奇偶数,负数也同样适用, num&1
var num=3;
!!(num & 1) // true
!!(num % 2) // true
字符串比较时间先后
var a = "2014-08-08";
var b = "2014-09-09";
console.log(a>b, a<b); // false true
let param1 = 1;
let param2 = 2;
[param1, param2] = [param2, param1];
console.log(param1) // 2
console.log(param2) // 1
使用解构删除不必要属性
有时候你不希望保留某些对象属性,也许是因为它们包含敏感信息或仅仅是太大了(just too big)。你可能会枚举整个对象然后删除它们,但实际上只需要简单的将这些无用属性赋值给变量,然后把想要保留的有用部分作为剩余参数就可以了。
下面的代码里,我们希望删除_internal和tooBig参数。我们可以把它们赋值给internal和tooBig变量,然后在cleanObject中存储剩下的属性以备后用。
let {_internal, tooBig, ...cleanObject} = {el1: '1', _internal:"secret", tooBig:{}, el2: '2', el3: '3'};
console.log(cleanObject); // {el1: '1', el2: '2', el3: '3'}
带有多个条件的 if 语句
把多个值放在一个数组中,然后调用数组的 includes 方法。
// bad
if (x === "abc" || x === "def" || x === "ghi" || x === "jkl") {
//logic
}
// better
if (["abc", "def", "ghi", "jkl"].includes(x)) {
//logic
}
条件查找简化
如果我们要基于不同的类型调用不同的方法,可以使用多个 else if 语句或 switch,但有没有比这更好的简化技巧呢?其实是前面的 switch 简化方式一样!
// bad
if (type === "test1") {
test1();
} else if (type === "test2") {
test2();
} else if (type === "test3") {
test3();
} else if (type === "test4") {
test4();
} else {
throw new Error("Invalid value " + type);
}
// better
var types = {
test1,
test2,
test3,
test4,
};
types[type] && types[type]();
顺序执行 promise
如果你有一堆异步或普通函数都返回 promise,要求你一个接一个地执行,怎么办?
async function getData() {
const promises = [fetch("url1"), fetch("url2"), fetch("url3"), fetch("url4")];
for (const item of promises) {
// 打印出promise
console.log(item);
}
// better
for await (const item of promises) {
// 打印出请求的结果
console.log(item);
}
}
将Object属性转成属性数组
const obj = { a: 1, b: 2, c: 3 };
Object.entries(obj);
// 输出
(3) [Array(2), Array(2), Array(2)]
0: (2) ["a", 1]
1: (2) ["b", 2]
2: (2) ["c", 3]
length: 3
Object.keys(obj);
(3) ["a", "b", "c"]
Object.values(obj);
(3) [1, 2, 3]