-1

谁能帮我理解我在做什么错误?或者帮我提供一个替代解决方案?

http://jsfiddle.net/mrrajesh1982/eynpu8rj/2/

  function isValidImageUrl(url, callback) {
    $('<img>', {
        src: url,
        load: function() {
            callback(true);
        },
        error: function() {
            callback(false);
        }
    });
}
var ndata = [{imgUrl: "https://library.barnard.edu/sites/default/files/paired_t_test_output_1_and_2.png"},{imgUrl: "url1"},{imgUrl: "http://statistics-help-for-students.com/How_do_I_report_paired_samples_T_test_data_in_APA_style_files/image002.jpg"}];


for (var i = 0; i < ndata.length; i++){
    var imageUrl = ndata[i].imgUrl;
    (function(pictureUrl){
        isValidImageUrl(pictureUrl, function(result) {
            if (!result) {
                ndata[i].imgUrl = "http://media.tcc.fl.edu/webcourses/ctll/Developing_Your_Teaching_Philosophy/examples.jpg";
                //I am getting error on this line as TypeError: ndata[i] is undefined

                //My question here is to how to update the ndata array obejct with valid image URL? 
            }
        });
    }(imageUrl));
}
console.log(JSON.stringify(ndata));// Expecting ndata[1].imgUrl should get updated inside self invoking function with valid image url
4

1 回答 1

0
  function isValidImageUrl(url, callback) {
    $('<img>', {
        src: url,
        load: function() {
            callback(true);
        },
        error: function() {
            callback(false);
        }
    });
}
var ndata = [{imgUrl: "https://library.barnard.edu/sites/default/files/paired_t_test_output_1_and_2.png"},{imgUrl: "url1"},{imgUrl: "http://statistics-help-for-students.com/How_do_I_report_paired_samples_T_test_data_in_APA_style_files/image002.jpg"}];


for (var i = 0; i < ndata.length; i++){
    var imageUrl = ndata[i].imgUrl;
    (function(pictureUrl, i){
        isValidImageUrl(pictureUrl, function(result) {
            if (!result) {
                ndata[i].imgUrl = "http://media.tcc.fl.edu/webcourses/ctll/Developing_Your_Teaching_Philosophy/examples.jpg";
                //I am getting error on this line as TypeError: ndata[i] is undefined

                //My question here is to how to update the ndata array obejct with valid image URL? 

            console.log(ndata);
            }
        });
    }(imageUrl, i));
}

除了传递之外imageUrl,您还需要传递i给您的匿名函数,否则在回调运行时它已经丢失了它的值。

另一件事,您正在运行console.log()回调之前运行。您需要从回调中登录。另请注意,不能保证它会按顺序返回。

于 2015-01-27T10:16:04.053 回答