从数组中获取随机元素返回相同的元素

Siv*_*ini 2 javascript random jquery

请参考以下代码.

for (var i = 0; i < elements.length; i++) 
{
     //var element = elements[Math.floor(Math.random()*elements.length)];
     this.animateSymbol(elements[Math.floor(Math.random()*elements.length)]);
}
Run Code Online (Sandbox Code Playgroud)

elements数组包含svg元素列表(circle/path/ellipse等).我想从elements数组中选择随机元素.

它在某些情况下返回相同的元素我想随机选择元素,不需要再次选择相同的元素.需要从该数组中选择不同的元素.

有什么问题 ?为什么它返回相同的索引和相同的元素?

谢谢,

湿婆

Mic*_*ary 8

随机数是随机的.无法保证您不会两次获得相同的随机数.事实上,当你将随机数转换为有限的整数范围时,你很可能会得到两次相同的数字.

您可以通过复制数组来解决此问题,然后每次从数组中获取值时,将其删除.我们还将生成随机索引的代码分解为单独的函数; 它在其他情况下也很方便:

// Return a random integer >= 0 and < n
function randomInt( n ) {
    return Math.floor( Math.random() * n );
}

var copy = elements.slice();
while( copy.length ) {
    var index = randomInt( copy.length );
    this.animateSymbol( copy[index] );
    copy.splice( index, 1 );
}
Run Code Online (Sandbox Code Playgroud)

只是为了好玩,这是你可以编写循环的另一种方式:

var copy = elements.slice();
while( copy.length ) {
    var index = randomInt( copy.length );
    this.animateSymbol( copy.splice( index, 1 )[0] );
}
Run Code Online (Sandbox Code Playgroud)

任何一个都做同样的事情.为了清晰起见,我有点像一步一步的方法,但是.splice()方法返回你删除的元素的数组非常方便.

这是您可以粘贴到JavaScript控制台进行测试的代码版本:

// Return a random integer >= 0 and < n
function randomInt( n ) {
    return Math.floor( Math.random() * n );
}

var elements = [ 'a', 'b', 'c', 'd', 'e' ];
var copy = elements.slice();
while( copy.length ) {
    var index = randomInt( copy.length );
    console.log( copy.splice( index, 1 )[0] );
}
console.log( 'Done' );
Run Code Online (Sandbox Code Playgroud)

这也值得一看Xotic750的答案.它使用Fisher-Yates shuffle将数组随机化.对于非常冗长的阵列,这可能更有效.