且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Javascript将数组复制到新数组

更新时间:2023-01-30 22:01:08

您可以使用 .slice 方法:

You can use the .slice method:

var old = ["Apples", "Bananas"];
var newArr = old.slice(0);
newArr.reverse(); 
// now newArr is ["Bananas", "Apples"] and old is ["Apples", "Bananas"]

Array.prototype.slice返回数组部分的浅表副本。给它0作为第一个参数意味着你要返回所有元素的副本(从索引0开始)

Array.prototype.slice returns a shallow copy of a portion of an array. Giving it 0 as the first parameter means you are returning a copy of all the elements (starting at index 0 that is)