Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
205 views
in Technique[技术] by (71.8m points)

javascript - 按值复制数组(Copy array by value)

When copying an array in JavaScript to another array:

(将JavaScript中的数组复制到另一个数组时:)

var arr1 = ['a','b','c'];
var arr2 = arr1;
arr2.push('d');  //Now, arr1 = ['a','b','c','d']

I realized that arr2 refers to the same array as arr1 , rather than a new, independent array.

(我意识到arr2指向与arr1相同的数组,而不是一个新的独立数组。)

How can I copy the array to get two independent arrays?

(如何复制数组以获取两个独立的数组?)

  ask by Dan translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use this:

(用这个:)

var newArray = oldArray.slice();

Basically, the slice() operation clones the array and returns a reference to a new array.

(基本上, slice()操作将克隆该数组并返回对新数组的引用。)

Also note that: (另请注意:)

For references, strings and numbers (and not the actual object), slice() copies object references into the new array.

(对于引用,字符串和数字(??而不是实际对象), slice()对象引用复制到新数组中。)

Both the original and new array refer to the same object.

(原始数组和新数组都引用同一对象。)

If a referenced object changes, the changes are visible to both the new and original arrays.

(如果引用的对象发生更改,则更改对新数组和原始数组均可见。)

Primitives such as strings and numbers are immutable, so changes to the string or number are impossible.

(字符串和数字之类的基元是不可变的,因此无法更改字符串或数字。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...