freeCodeCamp/curriculum/challenges/chinese/02-javascript-algorithms-an.../es6/use-the-spread-operator-to-...

2.4 KiB
Raw Blame History

id title challengeType videoUrl localeTitle
587d7b89367417b2b2512b48 Use the Spread Operator to Evaluate Arrays In-Place 1 使用Spread运算符来就地评估数组

Description

ES6引入了扩展运算符 它允许我们在需要多个参数或元素的位置扩展数组和其他表达式。下面的ES5代码使用apply()来计算数组中的最大值:
var arr = [6,89,3,45];
var maximus = Math.max.applynullarr; //返回89
我们必须使用Math.max.apply(null, arr)因为Math.max(arr)返回NaNMath.max()期望以逗号分隔的参数,但不是数组。扩展运算符使这种语法更易于阅读和维护。
const arr = [6,89,3,45];
const maximus = Math.max... arr; //返回89
...arr返回一个解压缩的数组。换句话说,它传播阵列。但是,扩展运算符只能在就地工作,就像在函数的参数或数组文字中一样。以下代码不起作用:
const spreaded = ... arr; //将抛出语法错误

Instructions

使用spread运算符将arr1所有内容复制到另一个数组arr2

Tests

tests:
  - text: <code>arr2</code>是<code>arr1</code>正确副本。
    testString: 'assert(arr2.every((v, i) => v === arr1[i]), "<code>arr2</code> is correct copy of <code>arr1</code>.");'
  - text: <code>...</code>传播运算符用于复制<code>arr1</code> 。
    testString: 'getUserInput => assert(getUserInput("index").match(/\[\s*...arr1\s*\]/g),"<code>...</code> spread operator was used to duplicate <code>arr1</code>.");'
  - text: 更改<code>arr1</code>时, <code>arr2</code>保持不变。
    testString: 'assert((arr1, arr2) => {arr1.push("JUN"); return arr2.length < arr1.length},"<code>arr2</code> remains unchanged when <code>arr1</code> is changed.");'

Challenge Seed

const arr1 = ['JAN', 'FEB', 'MAR', 'APR', 'MAY'];
let arr2;
(function() {
  "use strict";
  arr2 = []; // change this line
})();
console.log(arr2);

Solution

// solution required