无法在for循环中使用Javascript添加到数组中

时间:2013-01-02 22:30:19

标签: javascript arrays

我正在尝试编写一些代码来查找网页上的所有链接图像。到目前为止,我能够生成所有链接(imageLinks)的数组,但在下面的代码中,最终的console.log(linkedImages)总是显示一个空数组。

我无法解决的问题是我评论过“这有效/但这不起作用”:

我做错了什么?任何帮助都非常感谢这个有点菜鸟。谢谢!

//Create an array of all the links containing img tags
var imageLinks = $("img").parent("a").map(function () {
    var h = $(this).attr("href");
    return h;
}).get();
//This correctly shows all the links:
//console.log(imageLinks);
//Declare an array to hold all the linked images 
var linkedImages = [];
//Loop through all the links to see if they're images or not
for (var l = 0; l < imageLinks.length; l++) {
    var currLink = imageLinks[l];

    function myCallback(url, answer) {
        if (answer) {
            //This works:
            console.log(url + ' is an image!');
            //But this doesn't work
            linkedImages.push(url);
        } else {
            //alert(url+' is NOT an image!');
        }
    }

    function IsValidImageUrl(url, callback) {
        var img = new Image();
        img.onerror = function () {
            callback(url, false);
        }
        img.onload = function () {
            callback(url, true);
        }
        img.src = url
    }
    IsValidImageUrl(currLink, myCallback);
};
//HELP! This always evaluates as just "[]"
console.log(linkedImages);

1 个答案:

答案 0 :(得分:0)

@SLaks说的是什么。由于图像的加载是异步的,因此在加载图像之后才会触发回调。要解决这个问题,你可以使用jQuery中的$.Deferred(我假设你使用的是jQuery,因为代码中有$(...)):

    function callback(dfd, url, answer) {
        if (answer) {
            //This works:
            console.log(url+' is an image!');
            //But this doesn't work
            dfd.resolve(url);
        } else {
            //alert(url+' is NOT an image!');
            dfd.reject();
        }
    }

    //Create an array of all the links containing img tags
    var imageLinks = $("img").parent("a").map(function() {
        var h = $(this).attr("href");
        return h;
    }).get();

    //This correctly shows all the links:
    //console.log(imageLinks);

    //Declare an array to hold all the linked images 
    var linkedImages = [];

    //Loop through all the links to see if they're images or not
    var dfds = [];
    for (var l=0; l<imageLinks.length; l++) {
        var currLink = imageLinks[l];
        var dfd = $.Deferred();
        dfd.done(function(url) { linkedImages.push(url); });
        dfds.push(dfd.promise());

        (function(dfd, url) {
            var img = new Image();
            img.onerror = function() { callback(dfd, url, false); }
            img.onload =  function() { callback(dfd, url, true); }
            img.src = url
        })(dfd, currLink);
    };

    $.when.apply(null, dfds).done(function() {
         console.log(linkedImages);
    });

没有对此进行过测试,但是如何使用延迟达到目标的一般想法就在那里。