【发布时间】:2015-01-27 09:30:36
【问题描述】:
谁能帮我理解我在做什么错误? 或者帮我提供一个替代解决方案?
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
【问题讨论】:
-
i错误,您在对象更新之前登录。 -
@ Scimonster ,由于我已经制作了自调用功能,我希望它应该可以正常工作。你有可能完成这项工作吗?我会为你的帮助感到遗憾。我了解回调逻辑,但不知道如何在 for 循环中使用它?
标签: javascript closures self-invoking-function