10 个实用的 JavaScript 小技巧

我一直在寻找提高效率的新方法。JavaScript 总是充满令人出乎意料的惊喜。

1. 将 arguments 对象转换为数组

arguments对象是函数内部可访问的类似数组的对象,其中包含传递给该函数的参数的值。

但它与其他数组不同,我们可以访问其元素值并获得长度,但是不能在其上使用其他的数组方法。

幸运的是,我们可以将其转换为常规数组:

1var argArray = Array.prototype.slice.call(arguments);

2. 对数组中所有的值求和

我最初的想法是使用循环,但是那样做太费事了。

1var numbers = [3, 5, 7, 2];
2var sum = numbers.reduce((x, y) => x + y);
3console.log(sum); // returns 17

3. 条件短路

我们有以下代码:

1if (hungry) {
2    goToFridge();
3}

通过将变量与函数一起使用,我们可以使其更短:

1hungry && goToFridge()

4. 对条件使用逻辑或

我曾经在函数的开头声明自己的变量,只是为了避免在出现任何意外错误的情况下得到 undefined

1function doSomething(arg1){ 
2    arg1 = arg1 || 32; // 如果变量尚未设置,则 arg1 将以 32 作为默认值
3}

5. 逗号运算符

逗号运算符( , )用来评估其每个操作数(从左到右)并返回最后一个操作数的值。

 1let x = 1;
 2
 3x = (x++, x);
 4
 5console.log(x);
 6// expected output: 2
 7
 8x = (2, 3);
 9
10console.log(x);
11// expected output: 3

6. 用 length  调整数组大小

你可以调整数组大小或清空数组。

 1var array = [11, 12, 13, 14, 15];  
 2console.log(array.length); // 5  
 3
 4array.length = 3;  
 5console.log(array.length); // 3  
 6console.log(array); // [11,12,13]
 7
 8array.length = 0;  
 9console.log(array.length); // 0  
10console.log(array); // []

7. 通过数组解构对值进行交换

解构赋值语法是一种 JavaScript 表达式,可以将数组中的值或对象中的属性解压缩为不同的变量。

1let a = 1, b = 2
2[a, b] = [b, a]
3console.log(a) // -> 2
4console.log(b) // -> 1

8. 随机排列数组中的元素

我每天我都在洗牌’

1var list = [1, 2, 3, 4, 5, 6, 7, 8, 9];
2console.log(list.sort(function() {
3    return Math.random() - 0.5
4})); 
5// [4, 8, 2, 9, 1, 3, 6, 5, 7]

9. 属性名可以是动态的

你可以在声明对象之前分配动态属性。

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

10. 过滤唯一值

对于所有 ES6 爱好者,我们可以通过使用带有展开运算符的 Set 对象来创建一个仅包含唯一值的新数组。

1const my_array = [1, 2, 2, 3, 3, 4, 5, 5]
2const unique_array = [...new Set(my_array)];
3console.log(unique_array); // [1, 2, 3, 4, 5]

你有什么 JavaScript 技巧或窍门要分享吗?