我尝试使用jquery或javascript从数组中删除随机项,直到数组为空。我需要在每一次的随机项目中找出慰藉。基本上,我将从给定的数组中创建一个带有随机图像的元素,直到所有图像都创建完毕。
这是我尝试获取随机项并从数组中删除,但它没有遍历整个数组-我被难住了。
"load": function(){
var imgArray = ['brain', 'mitochondria', 'microsope', 'beaker', 'beaker-2', 'scientist', 'cell', 'atom', 'dropper'];
function randomItem(array){
var arrayLength = array.length+1;
console.log(arrayLength);
for(var i = 0;i<array.length;i++){
var item = array[Math.floor(Math.random()*array.length)];
array.pop(item);
console.log(array);
}
}
randomItem(imgArray);
},以下是我的控制台输出:
10
home.js:12 ["brain", "mitochondria", "microsope", "beaker", "beaker-2", "scientist", "cell", "atom"]
home.js:12 ["brain", "mitochondria", "microsope", "beaker", "beaker-2", "scientist", "cell"]
home.js:12 ["brain", "mitochondria", "microsope", "beaker", "beaker-2", "scientist"]
home.js:12 ["brain", "mitochondria", "microsope", "beaker", "beaker-2"]
home.js:12 ["brain", "mitochondria", "microsope", "beaker"]发布于 2016-03-18 03:27:14
函数Array.prototype.pop()将从最后一个元素中删除一个元素。因此在这种情况下,您必须使用Array.prototype.splice(indext,cnt),
for(var i = array.length-1;i>=0;i--){
array.splice(Math.floor(Math.random()*array.length), 1);
console.log(array);
}由于我们改变了数组,我们必须以相反的方式遍历它,这样索引就不会被折叠。
发布于 2016-03-18 03:31:07
当长度大于零时,只需随机创建索引并拼接即可。
var data = ["brain", "mitochondria", "microsope", "beaker", "beaker-2", "scientist", "cell", "atom"];
while (data.length) {
document.write(data.splice(data.length * Math.random() | 0, 1)[0] + '<br>');
}
发布于 2016-03-18 03:28:03
Array.prototype.pop从数组中删除最后一个元素,而不是特定的元素。要删除特定索引处的元素,可以使用Array.prototype.splice (参见:How do I remove a particular element from an array in JavaScript? )。
您还会遇到for(var i = 0;i<array.length;i++)的问题,因为每当您删除一个项时,array.length都会发生变化,您只能完成一半的数组,您可以在反向for ( var i = array.length; i--; )中循环,这样array.length只会在第一次迭代之前计算一次,或者您可以使用while循环while( array.length )。
将您的循环更改为:
while( array.length ) {
var index = Math.floor( Math.random()*array.length );
console.log( array[index] ); // Log the item
array.splice( index, 1 ); // Remove the item from the array
}https://stackoverflow.com/questions/36069870
复制相似问题