3.5 KiB
3.5 KiB
id, title, challengeType, videoUrl, localeTitle
id | title | challengeType | videoUrl | localeTitle |
---|---|---|---|---|
587d7b7b367417b2b2512b13 | Copy an Array with the Spread Operator | 1 | 使用Spread Operator复制数组 |
Description
slice()
允许我们选择要复制的数组元素,但在其他几个有用的任务中,ES6的新扩展运算符允许我们使用简单且高度可读的语法轻松地按顺序复制所有数组的元素。扩展语法看起来像这样: ...
在实践中,我们可以使用spread运算符来复制数组,如下所示: let thisArray = [true,true,undefined,false,null];
让thatArray = [... thisArray];
// thatArray等于[true,true,undefined,false,null]
// thisArray保持不变,与thatArray相同
Instructions
copyMachine
,它将arr
(数组)和num
(数字)作为参数。该函数应该返回一个由arr
的num
副本组成的新数组。我们为您完成了大部分工作,但它还没有正常工作。使用扩展语法修改函数以使其正常工作(提示:我们已经介绍过的另一种方法可能会派上用场!)。 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(["it works"], 3)</code>应该返回<code>[["it works"], ["it works"], ["it works"]]</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