简体   繁体   English

更改子阵列何时更新子阵列与创建新子阵列? [JavaScript]

[英]When does changing a sub-array update the sub-array vs. creating a new sub-array? [JavaScript]

I have a [Edit: JavaScript] code that uses a sub-array dataSelectedArray that tracks from my main data set mainArray .我有一个[编辑:JavaScript的],使用一个子阵列码dataSelectedArray从我的主要数据磁道设置mainArray The main data is stored as an array of arrays.主要数据存储为数组数组。

mainArray = [ [1,2,3],[3,4,2],[5,1,0] ];
dataSelectedArray=[];
for (var i=0; i<dataArray.length; i++) {
    if ( someLogic ) {
        dataSelectedArray.push(mainArray[i]);
    }
}

Thus, dataSelectedArray holds pointers to the values stored by mainArray .因此, dataSelectedArray保存指向mainArray存储的值的指针。 Later, I need to update mainArray by replacing it with data from updatedData .后来,我需要更新mainArray通过从数据替换它updatedData I need dataSelectedArray to also be updated.我还需要更新dataSelectedArray I can think of two ways to do this: update each mini-array as a set, or update each component.我可以想到两种方法来做到这一点:将每个小阵列更新为一个集合,或者更新每个组件。

 var mainArray = [ [1,2,3],[3,4,2],[5,1,0] ]; var dataSelectedArray=[]; for (var i=0; i<mainArray.length; i++) { if ( i<2 ) { dataSelectedArray.push(mainArray[i]); } } updatedData = [ [ 1,0,0],[7,4,2] ]; for (var index= 0; index < updatedData.length; index++) { // this doesn't update dataSelectedArray mainArray[index] = updatedData[index]; } console.log(mainArray[0]); console.log(dataSelectedArray[0]);

 var mainArray = [ [1,2,3],[3,4,2],[5,1,0] ]; var dataSelectedArray=[]; for (var i=0; i<mainArray.length; i++) { if ( i<2 ) { dataSelectedArray.push(mainArray[i]); } } updatedData = [ [ 1,0,0],[7,4,2] ]; for (var index= 0; index < updatedData.length; index++) { // this *does* update dataSelectedArray mainArray[index][0] = updatedData[index][0]; mainArray[index][1] = updatedData[index][1]; mainArray[index][2] = updatedData[index][2]; } console.log(mainArray[0]); console.log(dataSelectedArray[0]);

The first method doesn't update dataSelectedArray ...why not?第一种方法不更新dataSelectedArray ......为什么不呢? And is there a shorter (one-liner) way to do the second method?是否有更短的(单行)方法来执行第二种方法?

When you do:当你这样做时:

dataSelectedArray.push(mainArray[i]);

dataSelectedArray contains a reference to the sub-array. dataSelectedArray包含对子数组的引用。 This is not a reference to the location in mainArray where the original reference came from.不是mainArray中原始引用来自的位置的引用。 So reassigning mainArray[i] has no effect on the value in dataSelectedArray .因此重新分配mainArray[i]dataSelectedArray的值没有影响。

It's no different from when you have multiple variables referring to the same array:这与您有多个变量引用同一个数组时没有什么不同:

var a = [1, 2, 3];
var b = a; // a and b now refer to the same array
b[1] = 6;
console.log(a[1]); // Outputs 6
b = [7, 8, 9]; // b now refers to a different array
console.log(a[1]); // Still 6 -- a hasn't been modified

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

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