水牛的es6日记第四天【展开运算符】

ES6引入了spread运算符,它使我们可以在需要多个参数或元素的地方扩展数组和其他表达式。 下面的ES5代码使用apply()来计算数组中的最大值:

var arr = [6, 89, 3, 45];
var maximus = Math.max.apply(null, arr); // returns 89

我们必须使用Math.max.apply(null,arr),因为Math.max(arr)返回NaN。 Math.max()需要使用逗号分隔的参数,但不能使用数组。spread运算符使该语法更易于阅读和维护。

const arr = [6, 89, 3, 45];
const maximus = Math.max(...arr); // returns 89

… arr返回解压缩的数组。换句话说,它扩展了数组。但是,spread运算符只能在原位工作,就像在函数的自变量或数组文字中一样。以下代码不起作用:

const spreaded = ...arr; // will throw a syntax error

小测

使用传播运算符将arr1的所有内容复制到另一个数组arr2中。

const arr1 = ['JAN', 'FEB', 'MAR', 'APR', 'MAY'];
let arr2;

arr2 = [];  // Change this line

console.log(arr2);

答案

const arr1 = ['JAN', 'FEB', 'MAR', 'APR', 'MAY'];
let arr2;

arr2 = [...arr1];  // Change this line

console.log(arr2);

发布了60 篇原创文章 · 获赞 18 · 访问量 5217

猜你喜欢

转载自blog.csdn.net/szuwaterbrother/article/details/105613525