假设我创建了一个数组,如下所示:
var arr1 = ['one', 'two', 'three'];
我现在想创建另一个像这样的数组:
var arr2 = [arr1, 'four', 'five']
现在这是 arr2 的内容:
[Array(3), "four", "five"]
这不是我想要的。我希望内容如下所示:
['one', 'two', 'three', 'four', 'five']
我怎样才能做到这一点?
注意,我不是寻找像 concat 这样的函数,而是寻找一种将 arr1 作为 arr2 中的项目列出的方法,这样 arr1 中的所有项目都将作为单独的项目添加arr2 中的项目(我希望这是有道理的)。
感谢您提供的任何帮助。
最佳答案
使用 ES6 spread syntax ...
你完全可以做到这一点。
The spread syntax allows an expression to be expanded in places where multiple arguments (for function calls) or multiple elements (for array literals) or multiple variables (for destructuring assignment) are expected.
var arr1 = ['one', 'two', 'three'];
var arr2 = [...arr1, 'four', 'five']
console.log(arr2)
关于javascript - 如何在 JavaScript 中将数组作为项目添加到另一个数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44137546/