在For循环中制作的JQuery数组,所有元素都相同

时间:2016-04-21 05:34:19

标签: javascript jquery arrays

我是JQuery的新手,很抱歉,如果这是一个天真的问题。我试图随机化3个数字的数组,35次。每次我将3个数字的数组洗牌并写入控制台时,它看起来像是一个新的shuffle。但是,当我将每个新的shuffling添加到一个数组并打印其全部内容时,似乎该数组存在最后一个shuffle的35个副本。

提前致谢!

var arr2 = [0,1,2]; 

var seedArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35]

var arr2AggregateArray = [];

for (i = 0; i < 35; i++) { 
    seed = seedArray[i];
    shuffle(arr2,seed);
    console.log(arr2);
    arr2AggregateArray[i] =  arr2;
    console.log(arr2); 
}

console.log(arr2AggregateArray);

1 个答案:

答案 0 :(得分:5)

这一行:

arr2AggregateArray[i] =  arr2;

引用放入arr2 arr2AggregateArray,而不是副本。所有35个引用都引用相同的数组:

+−−−−−−−−−−−−−−−−−−−−+  
| arr2AggregateArray |  
+−−−−−−−−−−−−−−−−−−−−+              +−−−−−−+
| 0:  *ref*          |−−−+−+−+−+−+−>| arr2 |
| 1:  *ref*          |−−/ / /   /   +−−−−−−+
| 2:  *ref*          |−−−/ /   /    | 0: 2 |
| 3:  *ref*          |−−−−/   /     | 1: 0 |
| ...                |       /      | 2: 1 |
| 34: *ref*          |−−−−−−/       +−−−−−−+
+−−−−−−−−−−−−−−−−−−−−+

你需要复制一份。在这种情况下,由于它只包含基元(数字),因此浅复制将执行:

arr2AggregateArray[i] =  arr2.slice(0);

您尚未展示自己的shuffle功能,所以我认为它可以就地播放阵列。如果它返回一个 new 混洗数组,那么您就不需要上面的slice,但您只需要使用shuffle&#39; s返回值。