是否有内置的方法将一个列表附加到另一个列表中,如下所示:
var a = [1,2,3];
a.append([4,5]);
// now a is [1,2,3,4,5];
Run Code Online (Sandbox Code Playgroud)
concat()做类似的事情,但返回结果.我想要一些修改现有列表的东西push()
out*_*tis 31
push会工作,但你也需要使用apply.
var a = [1,2,3];
a.push.apply(a, [4,5])
Run Code Online (Sandbox Code Playgroud)
var list = [1, 2];
Run Code Online (Sandbox Code Playgroud)
人们已经告诉你如何做到这一点:
list.push.apply(list, [3, 4]);list = list.concat([4, 5]);但我想告诉ES6传播运营商:list.push(...[3, 4]);.
请记住,目前没有多少浏览器支持它(您可以使用转发器).
如果您使用的是ES6,则可以使用扩展运算符
例如:-
listOne = [1,2,3]
listTwo = [4,5,6]
listTwo.push(...listOne)
Run Code Online (Sandbox Code Playgroud)
因为我刚刚编写了一个 Web 应用程序,其中必须连接大量数组并且性能至关重要,所以我在这个 jsperf 中测试了哪种方法最快。结果非常有趣。
在我的测试中,我将 10 个元素添加到包含 10,000 个元素的列表或数组中。
以下是测试用例,从最快到最慢。结果是在 Chrome 62 中测量的,但 Firefox 47 的表现类似:
LinkedList.prototype.concat: 90,313,485 次/秒
list.concat(concatList);
// This function has to change only 1-2 refences
Run Code Online (Sandbox Code Playgroud)Array.prototype.push在for 循环中:3,794,962 次操作/秒
for (var i = 0, len = concatArr.length; i < len; i++) {
array.push(concatArr[i]);
}
// Probably fastest in real life
Run Code Online (Sandbox Code Playgroud)Array.prototype.push.apply: 2,193,469 次操作/秒
array.push.apply(array, concatArr);
Run Code Online (Sandbox Code Playgroud)Array.prototype.concat:22,701 次操作/秒
array = array.concat(concatArr);
Run Code Online (Sandbox Code Playgroud)不幸的是,如果您想将数组/列表连接到多个LinkedLists,则该版本不起作用。如果在每次连接操作之前都必须将数组复制到 a,那么它也没有任何好处。所以,对我来说,获胜者是for 循环。 LinkedListLinkedList
不使用Array.prototype.push.apply的原因之一是,如果串联数组太大,则会失败。根据这个答案,连接数组在 Firefox 中不能超过 500,000 个元素,在 Chrome 中不能超过 150,000 个元素。
我排除了扩展运算符,因为并非所有浏览器都支持它。在 Chrome 中,它的速度大约与 Firefox 一样快Array.prototype.push.apply,在 Firefox 中则稍慢一些。
| 归档时间: |
|
| 查看次数: |
24693 次 |
| 最近记录: |