在 for 循环中显示随机数组属性

Display random array properties in for loop

本文关键字:随机 数组 属性 显示 for 循环      更新时间:2023-09-26

我有一个循环forarray alerts字符串,我想知道我怎样才能alert它们randomly,所以它会运行gamesNames.length次,每次都以不同的随机顺序显示它们(不重复它们)在

JavaScript中?
  for (var i = 0; i < gamesNames.length; i++) {
            alert (gamesNames[i].Name + gamesNames[i].year );
        }

这里是Javascript中主要思想 http://www.javascriptkit.com/javatutors/arraysort.shtml 的链接

这是代码

...
gamesNames.sort(function() {return 0.5 - Math.random()}) ;
for (var i = 0; i < gamesNames.length; i++) {
      alert (gamesNames[i].Name + gamesNames[i].year );
}
...

我希望这有所帮助。

创建一个包含索引和随机数的项目的数组。通过对随机数进行排序来打乱它们,并使用索引来提醒项目:

var idx = [];
for (var i = 0; i < gamesNames.length; i++) {
  idx.push({ idx: i, rnd: Math.floor(Math.random() * 100000) });
}
idx.sort(function(x,y){ return x.rnd - y.rnd; });
for (var i = 0; i < idx.length; i++) {
  var j = idx[i].idx;
  alert (gamesNames[j].Name + gamesNames[j].year);
}

您可以轻松地将while-loop与 array.splice 结合使用:

var array = ["1", "2", "3", "4"];
while(array.length > 0)
{
    // Get a random index
    var index = Math.floor(Math.random() * array.length);
    // Append it to the DOM (or do whatever you want with it)
    $("body").append($("<p />").html(array[index]));
    // Remove it from the array
    array.splice(index, 1);
}

JSFiddle