简体   繁体   English

Javascript:如何在不更改引用的情况下修改数组中的每个元素

[英]Javascript: How to modify each element in array without changing the reference

let nestedArr = [[0,0],[0,0]]
let insideArr = nestedArr[0]
let targetArr = [1,1]

Basically I want to change the insideArr's elements to equal to targetArr , and it should change the first element of nestedArr too (because insideArr is refering to that).基本上我想将insideArr's元素更改为等于targetArr ,它也应该更改nestedArr的第一个元素(因为insideArr的是那个)。

insideArr = targetArr
insideArr = [..targetArr]

Above 2 approaches won't work because it will make insideArr pointing to new reference.以上两种方法都行不通,因为它会使insideArr指向新的引用。 I know using forEach to loop through insideArr and assign it one by one should work, but is there a better way?我知道使用forEach循环遍历insideArr并一个一个地分配它应该可以工作,但是有更好的方法吗? And BTW, should I avoid this kind of usage?顺便说一句,我应该避免这种用法吗?

If you must maintain insideArr as a reference to nestedArr[0] , you can use Array.prototype.splice() to mutate insideArr如果你必须维护insideArr作为对nestedArr[0]的引用,你可以使用Array.prototype.splice()来改变insideArr

 let nestedArr = [[0,0],[0,0]] let insideArr = nestedArr[0] let targetArr = [1,1] // Replace all of insideArr with targetArr insideArr.splice(0, insideArr.length, ...targetArr) console.log("still the same reference?", insideArr === nestedArr[0]) console.log("insideArr:", insideArr) console.log("nestedArr:", nestedArr)
 .as-console-wrapper { max-height: 100%;important; }

Assuming you have good reasons for keeping the reference the same - and sometimes there are, you can do:假设您有充分的理由保持参考相同 - 有时有,您可以这样做:

let nestedArr = [
  [0, 0],
  [0, 0]
];
let insideArr = nestedArr[0];
let targetArr = [1, 1];
insideArr.length = 0;
insideArr.unshift(...targetArr); // insideArr.push(...targetArr) works fine too
console.log(nestedArr);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM