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

在JavaScript中排序数组时出现奇怪的结果,javascript,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.

好的,在这里学习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.
//字符串或数组
var-strr=[1,5,3];
//更改了数组。
var cha=[];
var t=0;
/*将strr推入cha阵列
应该像
[
[1,5,3],
[1,5,3],
[1,5,3]
]
*/

对于(var i=0;i而言,您实际上是将同一数组推三次

推送
它的空心副本(因为它是一个原语数组)

演示

var-strr=[1,5,3];
var cha=[];
var t=0;
对于(变量i=0;i<3;i++){
cha.push(strr.slice());
}
(查中的a){
cha[a]=cha[a].排序(函数(){
返回Math.floor(Math.random()*100)-50;
});
}

console.log(cha);
数组cha包含对同一数组strr的三个引用。如果需要三个单独的strr数组,则需要克隆它们。cha.push(strr.slice(0));
cha.push( strr.slice() );