Tra*_*ler 12 javascript arrays jquery for-loop
我试图从数组中删除一个随机项,直到数组为空,使用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);
},
Run Code Online (Sandbox Code Playgroud)
这是我的控制台输出:
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"]
Run Code Online (Sandbox Code Playgroud)
Raj*_*amy 19
该函数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);
}
Run Code Online (Sandbox Code Playgroud)
因为我们正在改变数组,所以我们必须以相反的方式遍历它,这样索引就不会崩溃.
Array.prototype.pop从数组中删除最后一个元素,而不是特定元素。要删除特定索引处的元素,可以使用Array.prototype.splice(请参阅:如何在 JavaScript 中从数组中删除特定元素?)。
你也有一个问题for(var i = 0;i<array.length;i++),因为array.length每当你删除一个项目时就会发生变化,你只会遍历一半的数组,你可以反向循环for ( var i = array.length; i--; ),这样array.length在第一次迭代之前只评估一次,或者你可以使用一段时间环形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
}
Run Code Online (Sandbox Code Playgroud)
长度大于零时,只需进行随机索引和拼接即可。
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>');
}Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14331 次 |
| 最近记录: |