18
JavaScript无引用复制一个Array数组的每一个元素到另一个数组
source link: http://ourjs.com/detail/5bea74e9ac52fe63eba502b3?amp%3Butm_medium=referral
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
复制数组元素
如果目标数组不存在,可使用 slice/ concat 复制
var destinationArray = sourceArray.slice(); var destinationArray = sourceArray.concat();
如果目标数组存在,且想保持引用,可使用 push
destinationArray.push.apply(destinationArray, sourceArray);
元素无引用复制
如果数组中对象是object,以上方法复制的数组中的元素,还是相互引用的
var src = [ { name: 'a' }, { name: 'b' } ];
var tar = src.slice();
//更改 arr 中元素
src[0].name = 'c';
console.log(tar[0]);
> { name: "c" }
最简单的方法是使用 JSON 序列化来复制完全独立的数组
var cloneArray = JSON.parse(JSON.stringify(originalArray));
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK