常用js技巧

1,声明变量

1
let x, y = 20;

2,给多个变量赋值

1
let [a, b, c] = [5, 8, 12];

3,三元运算符

1
2
3
4
5
6
7
8
9
10
//Longhand
let marks = 26;
let result;
if(marks >= 30){
result = 'Pass';
}else{
result = 'Fail';
}
//Shorthand
let result = marks >= 30 ? 'Pass' : 'Fail';

4,默认值

如果预期值不正确的情况下,我们可以使用 OR(||) 短路运算来给一个变量赋默认值。

1
2
//Shorthand
let imagePath = getImagePath() || 'default.jpg';

5,与运算

如果你只有当某个变量为 true 时调用一个函数,那么你可以使用与 (&&)短路形式书写。

1
2
3
4
5
6
//Longhand
if (isLoggedin) {
goToHomepage();
}
//Shorthand
isLoggedin && goToHomepage();

6,双非位运算符 (~~)

向下取整 是Math.floor()方法的缩写。
双非位运算符只对 32 位整数有效,例如 (2**31)-1 = 2147483647。
所以对于任何大于 2147483647 的数字,双非位运算符 (~~) 都会给出错误的结果,这种情况下推荐使用 Math.floor() 方法。

1
2
3
4
//Longhand
const floor = Math.floor(6.8); // 6
// Shorthand
const floor = ~~6.8; // 6

7,找出数组中的最大和最小数字

1
2
3
const arr = [2, 8, 15, 4];
Math.max(...arr); // 15
Math.min(...arr); // 2

8,For 循环

为了遍历一个数组,我们一般使用传统的for循环。
我们可以使用for…of来遍历数组。为了获取每个值的索引,我们可以使用for…in循环。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
let arr = [10, 20, 30, 40];
//Longhand
for (let i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
//Shorthand
//for of loop
for (const val of arr) {
console.log(val);
}
//for in loop
for (const index in arr) {
console.log(arr[index]);
}
// 我们还可以使用for...in循环来遍历对象属性。
let obj = {x: 20, y: 50};
for (const key in obj) {
console.log(obj[key]);
}

9,合并数组

1
2
3
4
5
6
7
let arr1 = [20, 30];
//Longhand
let arr2 = arr1.concat([60, 80]);
// [20, 30, 60, 80]
//Shorthand
let arr2 = [...arr1, 60, 80];
// [20, 30, 60, 80]