当前位置: 动力学知识库 > 问答 > 编程问答 >

Shuffle multidimensional array in javascript gets dublicated

问题描述:

I have a problem with shuffling an array in javascript.

A multidimensional array gets its row shuffled twice and the result is EXACT same numbers returned.

I do not want same numbers, but I want different shuffled results.

this.pairs = [

[0, 1, 2, 3]

];

this.shuffled = [

[shuffle(this.pairs[0])],

[shuffle(this.pairs[0])]

];

console.log(this.shuffled);

Where shuffle function is:

function shuffle(array) {

for (var i = array.length - 1; i > 0; i--) {

var j = Math.floor(Math.random() * (i + 1));

var temp = array[i];

array[i] = array[j];

array[j] = temp;

}

return array;}

It just randomized the array values.

Now when I try shuffle([0,1,2,3]) it works if I just call the same function twice.

But when I write shuffle(this.pairs[0]); it returns exact same values no matter how many times I call it. Any help?

UPDATE

I then tried as suggested to add them in different variables, still does not work.

this.pairs = [

[0, 1],

[0, 1]

];

var level1 = this.pairs[0];

var level2 = this.pairs[0];

this.shuffled = [

shuffle(level1),

shuffle(level2)

];

console.log(this.shuffled);

Same goes for this:

this.pairs = [

[0, 1],

[0, 1]

];

var level1 = shuffle(this.pairs[0]);

var level2 = shuffle(this.pairs[0]);

this.shuffled = [

level1,

level2

];

console.log(this.shuffled);

网友答案:

The issue is you are using this.name, It will point to same reference always So result will be overridden by last shuffle call. So you need to copy the value after each shuffling to a new variable.

网友答案:

Try to assign shuffle function result to a variable.

分享给朋友:
您可能感兴趣的文章:
随机阅读: