2.2 KiB
2.2 KiB
id, title, challengeType, forumTopicId, localeTitle
id | title | challengeType | forumTopicId | localeTitle |
---|---|---|---|---|
587d7b89367417b2b2512b48 | Use the Spread Operator to Evaluate Arrays In-Place | 1 | 301222 | 使用 spread 运算符展开数组项 |
Description
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()
函数需要传入的是一系列由逗号分隔的参数,而不是一个数组。
展开操作符可以提升代码的可读性,这对后续的代码维护是有积极作用的。
const arr = [6, 89, 3, 45];
const maximus = Math.max(...arr); // returns 89
...arr
返回了一个“打开”的数组。或者说它 展开 了数组。
然而,展开操作符只能够在函数的参数中,或者数组之中使用。下面的代码将会报错:
const spreaded = ...arr; // will throw a syntax error
Instructions
arr1
中的内容都赋值到arr2
中去。
Tests
tests:
- text: <code>arr2</code>的值是由<code>arr1</code>拷贝而来的。
testString: assert(arr2.every((v, i) => v === arr1[i]));
- text: 用<code>...</code>展开操作符来赋值<code>arr1</code>。
testString: assert(code.match(/Array\(\s*\.\.\.arr1\s*\)|\[\s*\.\.\.arr1\s*\]/));
- text: 当<code>arr1</code>改变的时候,<code>arr2</code>不会改变。
testString: assert((arr1, arr2) => {arr1.push('JUN'); return arr2.length < arr1.length});
Challenge Seed
const arr1 = ['JAN', 'FEB', 'MAR', 'APR', 'MAY'];
let arr2;
arr2 = []; // change this line
console.log(arr2);
Solution
const arr1 = ['JAN', 'FEB', 'MAR', 'APR', 'MAY'];
let arr2;
arr2 = [...arr1];