--- id: 587d7da9367417b2b2512b67 title: Add Elements to the End of an Array Using concat Instead of push challengeType: 1 forumTopicId: 301226 localeTitle: 使用 concat 而不是 push 将元素添加到数组的末尾 --- ## Description
函数式编程就是创建和使用具有不变性的函数。 上一个挑战介绍了concat方法,这是一种在不改变原始数组的前提下,将数组组合成新数组的方法。将concat方法与push方法做比较,Push将元素添加到调用它的数组的末尾,这样会改变该数组。举个例子: ```js var arr = [1, 2, 3]; arr.push([4, 5, 6]); // arr is changed to [1, 2, 3, [4, 5, 6]] // Not the functional programming way ``` Concat方法可以将新项目添加到数组末尾,而不产生任何变化。
## Instructions
修改nonMutatingPush函数,用concat替代pushnewItem添加到original末尾,该函数应返回一个数组。
## Tests
```yml tests: - text: 应该使用concat方法。 testString: assert(code.match(/\.concat/g)); - text: 不能使用push方法。 testString: assert(!code.match(/\.push/g)); - text: 不能改变first数组。 testString: assert(JSON.stringify(first) === JSON.stringify([1, 2, 3])); - text: 不能改变second数组。 testString: assert(JSON.stringify(second) === JSON.stringify([4, 5])); - text: nonMutatingPush([1, 2, 3], [4, 5])应返回[1, 2, 3, 4, 5]。 testString: assert(JSON.stringify(nonMutatingPush([1, 2, 3], [4, 5])) === JSON.stringify([1, 2, 3, 4, 5])); ```
## Challenge Seed
```js function nonMutatingPush(original, newItem) { // Add your code below this line return original.push(newItem); // Add your code above this line } var first = [1, 2, 3]; var second = [4, 5]; nonMutatingPush(first, second); ```
## Solution
```js function nonMutatingPush(original, newItem) { return original.concat(newItem); } var first = [1, 2, 3]; var second = [4, 5]; nonMutatingPush(first, second); ```