好的,只是在这里学习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.
最佳答案
您实际上是在推动同一阵列三次。push
它的空心副本(因为它是基元数组)
cha.push( strr.slice() );
演示版
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);