Javascript:使用 for 循环将数组推送到数组上

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9005778/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 08:22:18  来源:igfitidea点击:

Javascript: push array onto array with for loop

javascriptarraysloopsfor-loop

提问by Eric Porterfield

Please explain this to me. I'm trying to create an array of arrays with a for loop. When it didn't work, I tried simplifying the code to understand what Javascript is doing, but the simple code doesn't make sense either.

请向我解释这一点。我正在尝试使用 for 循环创建一个数组数组。当它不起作用时,我尝试简化代码以了解 Javascript 在做什么,但简单的代码也没有任何意义。

function test(){
    var sub_array = [];
    var super_array =[];
    for (var i=1;i<=3;i++){
        sub_array.push(i);
        super_array.push(sub_array);
    }
    alert(super_array);
}

I expect to see [1; 1,2; 1,2,3]. Instead I get [1,2,3; 1,2,3; 1,2,3]. I get the same phenomenon if I loop 0-2 and assign by index.

我希望看到 [1; 1,2; 1,2,3]。相反,我得到 [1,2,3; 1、2、3;1,2,3]。如果我循环 0-2 并按索引分配,我会得到同样的现象。

回答by Frédéric Hamidi

You're always pushing a reference to the same array into your super-array.

你总是把对同一个数组的引用推送到你的超级数组中。

To solve that problem, you can use slice()to clone the sub-array before pushing it:

为了解决这个问题,你可以在推送之前使用slice()来克隆子数组:

function test() {
    var sub_array = [];
    var super_array = [];
    for (var i = 1; i <= 3; i++) {
        sub_array.push(i);
        super_array.push(sub_array.slice(0));
    }
    alert(super_array);
}

EDIT:As Dan D. rightfully points out below, you can also call concat()without arguments instead of slice(0). It's faster according to this article(I did not measure it myself):

编辑:正如 Dan D. 在下面正确指出的那样,您也可以不带参数调用concat()而不是slice(0). 根据这篇文章更快(我没有自己测量):

for (var i = 1; i <= 3; i++) {
    sub_array.push(i);
    super_array.push(sub_array.concat());
}

回答by Pointy

When you push "sub_array", you're not pushing a copyof it. You end up with the same array three times in "super_array". (I should say that you're pushing a referenceto the same array three times.)

当您推送“sub_array”时,您并没有推送它的副本。你最终在“super_array”中得到了三次相同的数组。(我应该说您将引用对同一个数组推送了三次。)

You could do this:

你可以这样做:

    // ...
    super_array.push(sub_array.slice(0));

to make a copy.

复制。

回答by japrescott

well. You have to understand, that Array, Objects, Functions, etc. are references in javascript (only Numbers(Int,Floats,etc) and Strings are passed "by-value", which means, that the value is copied/duplicated)! if you have an var a=[];, und say var b=aand add b.push("bla"), then alerting a, will show you the "bla" entry, even though you added it to b. In other words; a and b is to javascript like a note on the frige from mom saying "the sandwhich on the left is for you." And then you know, that to take the left one and not just any random sandwich from the fridge. She also could have written another note (variable b) on your house' door, so that you knew where to go and look for the sandwich if you are in a hurry. If she would have stuck a sandwich to the door.. well, that would be ackward. And JS thinks the same about it :)

好。您必须了解,数组、对象、函数等是 javascript 中的引用(只有数字(Int、Floats 等)和字符串是“按值”传递的,这意味着该值被复制/复制)!如果您有var a=[];, 和说var b=a并添加b.push("bla"),然后提醒 a,即使您将其添加到 b,也会向您显示“bla”条目。换句话说; a 和 b 对 javascript 来说就像是妈妈在冰箱上的一张纸条,上面写着“左边的三明治是给你的”。然后你知道,从冰箱里拿出左边的,而不是随便的三明治。她还可以在你家的门上写下另一个注释(变量 b),这样你就知道如果你赶时间去哪里找三明治。如果她会在门上放一个三明治……好吧,那就太糟糕了。JS 也是这么想的 :)

so the solution to your problem is as fallows;

所以你的问题的解决方案是休耕;

function test(){
    var super_array =[];
    for (var i=1;i<=3;i++){
        var subarray=[];
        for (var u=1;u<=4-i;u++){
            sub_array.push(u);
            super_array.push(subarray);
        }
    }
    alert(super_array);
}

by redefining the subarray, you create a new reference. So that the variable b (the second note on the hous' door) now points in the direction of a different sandwich - maybe dad's sandwich.

通过重新定义子数组,您可以创建一个新的引用。所以变量 b(房子门上的第二个音符)现在指向另一个三明治的方向——也许是爸爸的三明治。

I hope I could help you understand this.

我希望我能帮助你理解这一点。

回答by Thomas Johan Eggum

Note that you are pushing the same array into super_array for each iteration in the for-loop. Try instead the following:

请注意,对于 for 循环中的每次迭代,您都将相同的数组推送到 super_array 中。请尝试以下操作:

function test(){
    var sub_array = [];
    var super_array =[];
    for (var i=1;i<=3;i++){
        sub_array = sub_array.slice(0,sub_array.length);
        sub_array.push(i);
        super_array.push(sub_array);
    }
    alert(super_array);
}

回答by Selvakumar Arumugam

It is same sub_array that you are adding to the super_array. So why it has to be different.

它与您添加到 super_array 的 sub_array 相同。那么为什么它必须是不同的。

You are not creating a new array and pushing into a super_array.

您不是在创建新数组并推入 super_array。

回答by James Wiseman

sub_arrayis stored as a reference in super_arraythis means that when you change sub_arraythe change is reflected inside super_array

sub_array存储为参考,super_array这意味着当您更改时sub_array,更改会反映在内部super_array