在JavaScript中排序数组数组时的奇怪结果

时间:2018-03-01 10:23:14

标签: javascript

好的,只是在这里学习JavaScript,我知道我应该寻找答案,但我甚至无法弄清楚我应该搜索什么,我完全不知道为什么会发生这种情况

  // string or array
 var strr=[1,5,3];
//changed array.
var cha=[];
var t=0;
/*push strr into the cha array
should look like
[
[1,5,3],
[1,5,3],
[1,5,3]
]
*/
for(var i=0;i<3;i++){
cha.push(strr);
}
//shuffle each element one by one
for(a in cha){
cha[a]=cha[a].sort(function()
    {return Math.floor(Math.random()*100)-50;
    });
}
//each element should be a re arranged array with the     same elemnts of strr
// Like 135, 351, 153 for example
console.log(cha);

// But it arranges all of the elements the same. the shuffle     changed the order of strr, but not each of cha...
// Like 351,351,351 for example, they are randomized, but all the same.

1 个答案:

答案 0 :(得分:3)

你实际上是推三次相同的数组

push它的空心副本(因为它是一个基元数组)

cha.push( strr.slice() );

<强>演示

&#13;
&#13;
var strr = [1, 5, 3];
var cha = [];
var t = 0;
for (var i = 0; i < 3; i++) {
  cha.push(strr.slice());
}
for (a in cha) {
  cha[a] = cha[a].sort(function() {
    return Math.floor(Math.random() * 100) - 50;
  });
}
console.log(cha);
&#13;
&#13;
&#13;