slice()
已经能让我们从一个数组中选择一些元素来复制到新数组中了,而 ES6 中又新引入了一个简洁且可读性强的语法展开运算符(spread operator),它能让我们方便地复制数组中的所有元素。展开语法是这样的:...
在实践中,我们可以这样用展开运算符来复制一个数组:
```js
let thisArray = [true, true, undefined, false, null];
let thatArray = [...thisArray];
// thatArray 等于 [true, true, undefined, false, null]
// thisArray 保持不变,等于 thatArray
```
copyMachine
函数,它接受arr
(一个数组)和num
(一个数字)作为输入参数。该函数应该返回一个由num
个arr
组成的新数组。我们已经为你写好了大部分的代码,但它还不能正确地工作。请修改这个函数,使用展开语法,使该函数正确工作(提示:我们已经学到过的一个方法很适合用在这里!)
copyMachine([true, false, true], 2)
应该返回[[true, false, true], [true, false, true]]
'
testString: assert.deepEqual(copyMachine([true, false, true], 2), [[true, false, true], [true, false, true]]);
- text: 'copyMachine([1, 2, 3], 5)
应该返回[[1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]]
'
testString: assert.deepEqual(copyMachine([1, 2, 3], 5), [[1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]]);
- text: 'copyMachine([true, true, null], 1)
应该返回[[true, true, null]]
'
testString: assert.deepEqual(copyMachine([true, true, null], 1), [[true, true, null]]);
- text: 'copyMachine(["it works"], 3)
应该返回[["it works"], ["it works"], ["it works"]]
'
testString: assert.deepEqual(copyMachine(['it works'], 3), [['it works'], ['it works'], ['it works']]);
- text: copyMachine
函数中应该对数组arr
使用spread operator
。
testString: assert(removeJSComments(code).match(/\.\.\.arr/));
```