转自:微点阅读 https://www.weidianyuedu.com
一直在寻找提高效率的新方法。而且 JavaScript 总是能给人带来惊喜。将 arguments 对象转换为数组
arguments 对象是函数内部可访问的类似数组的对象,其中包含传递给该函数的参数的值。
与其他数组不同,这里我们可以访问值并获得长度(length),但是不能在其上使用其他数组方法。
幸运的是,我们可以将其转换为常规数组:
var argArray = Array.prototype.slice.call(arguments);
对数组中的所有值求和 我一开始想到的是使用一个循环,但是那样会很浪费。
var numbers = [3, 5, 7, 2];var sum = numbers.reduce((x, y) => x + y);console.log(sum); // returns 17
条件短路 我们有以下代码:
if(hungry) {goToFridge();}
我们可以进一步简化代码,同时使用变量和函数:
hungry&& goToFridge()
对条件使用或(OR)逻辑我以前在函数开始时声明变量,只是为了避免在出现意外错误时遇到 undefined。
function doSomething(arg1){ arg1= arg1 || 32; //if it"s not already set, arg1 will have 32 as a default value}
逗号运算符 逗号运算符(,)用来计算其每个操作数(从左到右)并返回最后一个操作数的值。
let x =1;x = (x++, x);console.log(x);// expected output: 2x = (2, 3);console.log(x);// expected output: 3
使用 length 调整数组大小 你可以调整大小或清空数组。
var array = [11, 12, 13, 14, 15];console.log(array.length); //5array.length=3;console.log(array.length); //3console.log(array); // [11,12,13]array.length=0;console.log(array.length); //0console.log(array); // []
使用数组解构来交换值。 解构赋值语法是一种 JavaScript 表达式,可以将数组中的值或对象中的属性解包为不同的变量。
let a =1, b =2[a, b] = [b, a]console.log(a) // ->2console.log(b) // ->1
随机排列数组中的元素
var list = [1, 2, 3, 4, 5, 6, 7, 8, 9];console.log(list.sort(function() { return Math.random() - 0.5}));// [4, 8, 2, 9, 1, 3, 6, 5, 7]
属性名称可以是动态的你可以在声明对象之前分配一个动态属性。
const dynamic="color";var item = { brand: "Ford", [dynamic]: "Blue"}console.log(item);// { brand: "Ford", color: "Blue" }
过滤唯一值对于所有 ES6 爱好者而言,我们可以使用带有 Spread 运算符的 Set 对象来创建一个仅包含唯一值的新数组。
const my_array = [1, 2, 2, 3, 3, 4, 5, 5]const unique_array = [...newSet(my_array)];console.log(unique_array); // [1, 2, 3, 4, 5]