使用splice(0)复制数组 [英] using splice(0) to duplicate arrays
问题描述
我有两个数组:ArrayA和ArrayB.我需要将ArrayA复制到ArrayB中(而不是创建引用),并且我一直在使用 .splice(0)
,但是我注意到它似乎从初始数组中删除了元素.>
在控制台中,当我运行以下代码时:
var ArrayA = [];var ArrayB = [];ArrayA.push(1);ArrayA.push(2);ArrayB = ArrayA.splice(0);alert(ArrayA.length);
警报显示为0 . .splice(0)
??
感谢您的见识.
您要使用 slice()
( MDN文档)!
ArrayB = ArrayA.slice(0);
slice()
保持原始数组不变,仅创建一个副本.
splice()
只是通过插入或删除元素来修改原始数组.
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.
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)
??
Thanks for your insight.
You want to use slice()
(MDN docu) and not splice()
(MDN docu)!
ArrayB = ArrayA.slice(0);
slice()
leaves the original array untouched and just creates a copy.
splice()
on the other hand just modifies the original array by inserting or deleting elements.
这篇关于使用splice(0)复制数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!