Javascript 从数组创建新元素,直到数组每秒为空
尝试使用每隔一秒随机选择的数组中的项创建元素,直到数组为空。当我没有将元素附加到dom中时,为什么我的函数可以工作,但当我添加到dom中时,数组就会变大,并最终破坏dom 我的计划是最终创建一个具有图像的新对象,css具有随机xy位置,然后使用对象值向dom添加一个新元素 基本上,我尝试每秒向dom添加随机图像,并让它们在数组为空之前进行动画处理 任何帮助都将不胜感激,谢谢Javascript 从数组创建新元素,直到数组每秒为空,javascript,jquery,arrays,loops,Javascript,Jquery,Arrays,Loops,尝试使用每隔一秒随机选择的数组中的项创建元素,直到数组为空。当我没有将元素附加到dom中时,为什么我的函数可以工作,但当我添加到dom中时,数组就会变大,并最终破坏dom 我的计划是最终创建一个具有图像的新对象,css具有随机xy位置,然后使用对象值向dom添加一个新元素 基本上,我尝试每秒向dom添加随机图像,并让它们在数组为空之前进行动画处理 任何帮助都将不胜感激,谢谢 "load": function(){ var imgArray = ['brain', 'mit
"load": function(){
var imgArray = ['brain', 'mitochondria', 'microscope', 'beaker', 'beaker-2', 'scientist', 'cell', 'atom', 'dropper'];
window.setInterval(function(){
var imgItem;
if( imgArray.length >= 1 ) {
var index = Math.floor( Math.random()*imgArray.length );
console.log( imgArray[index] ); // Log the item
imgItem = ( imgArray[index] ); // Log the item
imgArray.splice( index, 1 ); // Remove the item from the array
// $('form').append('<img class="img-animation" src="img/science/'+ imgItem +'.svg" alt="'+ imgItem +'">');
}
}, 1000);
},
如果我将新图像添加到dom中,它最终将崩溃,循环将永远持续下去,这对我来说毫无意义。好吧,您正在设置一个间隔,它将继续调用自己来检查数组是否每隔一秒钟空一次,即使这不是问题,我建议您执行以下操作:
var imgArray = ['brain', 'mitochondria', 'microscope', 'beaker', 'beaker-2', 'scientist', 'cell', 'atom', 'dropper'];
var getAllRandomly = function(arr) {
if (arr.length) {
var index = Math.floor(Math.random() * arr.length);
console.log(arr[index]); // Log the item
imgItem = (arr[index]); // Log the item
imgArray.splice(index, 1); // Remove the item from the array
setTimeout(function() {
getAllRandomly(arr);
}, 1000);
}
else {
console.log('Array is empty');
}
};
getAllRandomly(imgArray);
这样,函数将调用自身并每秒返回一个结果,直到数组为空
现在我们来看真正的问题:
您的“load”函数可能被多次调用,使用同一数组设置了很多间隔。如果循环真的是无限的,那么它可能会以某种方式调用自己。
尝试在加载函数中只保留一个控制台日志,然后运行脚本以查看日志是否多次出现。您是否考虑过在每次迭代中记录数组的内容,然后它可能会告诉您出错的原因/位置。为了防止无限循环,请在
if
中使用另一个变量,例如:if(imgArray.length&&iterationLimit)
(例如,初始化iterationLimit=10
后),该变量只允许10次迭代;在这两种情况下,0
都是错误的,因此,一旦其中一个数字达到0
时,if
的条件将是false
并停止)。我还想知道这个“加载”是否正确更新DOM后会重新调用回调。我使用Meteor作为我的框架,但我不了解您如何实现iterationLimit。我假设我应该在循环中的每次迭代中将限制减少一次?这看起来是循环添加到imgItem变量中的结果,因为图像开始成对出现,好像每次迭代都要加倍。这正是我想要实现的,非常感谢!
var imgArray = ['brain', 'mitochondria', 'microscope', 'beaker', 'beaker-2', 'scientist', 'cell', 'atom', 'dropper'];
var getAllRandomly = function(arr) {
if (arr.length) {
var index = Math.floor(Math.random() * arr.length);
console.log(arr[index]); // Log the item
imgItem = (arr[index]); // Log the item
imgArray.splice(index, 1); // Remove the item from the array
setTimeout(function() {
getAllRandomly(arr);
}, 1000);
}
else {
console.log('Array is empty');
}
};
getAllRandomly(imgArray);