javascript 使用 splice(0) 复制数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12073119/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 15:14:46  来源:igfitidea点击:

using splice(0) to duplicate arrays

javascript

提问by frenchie

I have two arrays: ArrayA and ArrayB. I need to copy ArrayA into ArrayB (as opposed to create a reference) and I've been using .splice(0)but I noticed that it seems to removes the elements from the initial array.

我有两个数组:ArrayA 和 ArrayB。我需要将 ArrayA 复制到 ArrayB (而不是创建引用),我一直在使用,.splice(0)但我注意到它似乎从初始数组中删除了元素。

In the console, when I run this code:

在控制台中,当我运行此代码时:

var ArrayA = [];
var ArrayB = [];

ArrayA.push(1);
ArrayA.push(2);

ArrayB = ArrayA.splice(0);

alert(ArrayA.length);

the alert shows 0. What am I doing wrong with .splice(0)??

警报显示 0。我做错了什么.splice(0)??

Thanks for your insight.

感谢您的洞察力。

回答by Sirko

You want to use slice()(MDN docu) and not splice()(MDN docu)!

您想使用slice()MDN docu)而不是splice()MDN docu)!

ArrayB = ArrayA.slice(0);

slice()leaves the original array untouched and just creates a copy.

slice()保持原始数组不变,只创建一个副本。

splice()on the other hand just modifies the original array by inserting or deleting elements.

splice()另一方面只是通过插入或删除元素来修改原始数组。

回答by Imp

splice(0)grabs all the items from 0onwards (i.e. until the last one, i.e. all of them), removesthem from the original array and returns them.

splice(0)0以后获取所有项目(即直到最后一个,即所有项目),从原始数组中删除它们并返回它们。

回答by KooiInc

You are looking for slice:

您正在寻找slice

var a = [1,2,3,4,5]
   ,b = a.slice();
//=> a = [1,2,3,4,5], b = [1,2,3,4,5]

you can use splice, but it will destroyyour original array:

您可以使用splice,但它会破坏您的原始数组:

var a = [1,2,3,4,5]
   ,b = a.splice(0);
//=> a = [], b = [1,2,3,4,5]