从数组创建新元素,直到每秒数组为空

时间:2016-03-18 14:50:23

标签: javascript jquery arrays loops

尝试使用每隔一秒随机选择的数组中的项创建元素,直到数组为空。我难以理解为什么我的功能工作时,我没有将元素附加到dom但是只要我添加到dom,数组就会变得更大并最终崩溃dom。

我的计划是最终创建一个具有图像的新对象,css具有随机​​xy位置,然后使用对象值将新元素附加到dom。

基本上我试图每秒向dom添加随机图像并让它们进出动画直到数组为空。

非常感谢任何帮助,谢谢。

    "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);

    },

当我不添加新图像时,这是控制台:

home.js:11 beaker
home.js:11 dropper
home.js:11 microscope
home.js:11 beaker-2
home.js:11 atom
home.js:11 brain
home.js:11 scientist
home.js:11 cell
home.js:11 mitochondria

如果我将新图像添加到dom中,它最终会崩溃并且循环会一直持续下去,这对我来说毫无意义。

1 个答案:

答案 0 :(得分:1)

好吧,你正在设置一个间隔,它会一直调用自己检查数组是否为空后每隔一秒,即使这不是问题,我建议你做这样的事情:

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'函数可能被多次调用,使用相同的数组设置了很多间隔。如果循环真的是无限的,那么它可能会以某种方式调用自身。 尝试在加载功能上只保留一个控制台日志,然后运行脚本以查看日志是否多次出现。

相关问题