freeCodeCamp/curriculum/challenges/chinese/02-javascript-algorithms-an.../basic-data-structures/copy-an-array-with-the-spre...

3.5 KiB
Raw Blame History

id title challengeType videoUrl localeTitle
587d7b7b367417b2b2512b13 Copy an Array with the Spread Operator 1 使用Spread Operator复制数组

Description

虽然slice()允许我们选择要复制的数组元素但在其他几个有用的任务中ES6的新扩展运算符允许我们使用简单且高度可读的语法轻松地按顺序复制所有数组的元素。扩展语法看起来像这样: ...在实践中我们可以使用spread运算符来复制数组如下所示
let thisArray = [truetrueundefinedfalsenull];
让thatArray = [... thisArray];
// thatArray等于[truetrueundefinedfalsenull]
// thisArray保持不变与thatArray相同

Instructions

我们定义了一个函数copyMachine ,它将arr (数组)和num (数字)作为参数。该函数应该返回一个由arrnum副本组成的新数组。我们为您完成了大部分工作,但它还没有正常工作。使用扩展语法修改函数以使其正常工作(提示:我们已经介绍过的另一种方法可能会派上用场!)。

Tests

tests:
  - text: '<code>copyMachine([true, false, true], 2)</code>应返回<code>[[true, false, true], [true, false, true]]</code>'
    testString: 'assert.deepEqual(copyMachine([true, false, true], 2), [[true, false, true], [true, false, true]], "<code>copyMachine([true, false, true], 2)</code> should return <code>[[true, false, true], [true, false, true]]</code>");'
  - text: '<code>copyMachine([1, 2, 3], 5)</code>应返回<code>[[1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]]</code>'
    testString: 'assert.deepEqual(copyMachine([1, 2, 3], 5), [[1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]], "<code>copyMachine([1, 2, 3], 5)</code> should return <code>[[1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]]</code>");'
  - text: '<code>copyMachine([true, true, null], 1)</code>应该返回<code>[[true, true, null]]</code>'
    testString: 'assert.deepEqual(copyMachine([true, true, null], 1), [[true, true, null]], "<code>copyMachine([true, true, null], 1)</code> should return <code>[[true, true, null]]</code>");'
  - text: '<code>copyMachine([&quot;it works&quot;], 3)</code>应该返回<code>[[&quot;it works&quot;], [&quot;it works&quot;], [&quot;it works&quot;]]</code>'
    testString: 'assert.deepEqual(copyMachine(["it works"], 3), [["it works"], ["it works"], ["it works"]], "<code>copyMachine(["it works"], 3)</code> should return <code>[["it works"], ["it works"], ["it works"]]</code>");'
  - text: <code>copyMachine</code>函数应该使用带有数组<code>arr</code>的<code>spread operator</code>
    testString: 'assert.notStrictEqual(copyMachine.toString().indexOf(".concat(_toConsumableArray(arr))"), -1, "The <code>copyMachine</code> function should utilize the <code>spread operator</code> with array <code>arr</code>");'

Challenge Seed

function copyMachine(arr, num) {
  let newArr = [];
  while (num >= 1) {
    // change code below this line

    // change code above this line
    num--;
  }
  return newArr;
}

// change code here to test different cases:
console.log(copyMachine([true, false, true], 2));

Solution

// solution required