Im JavaScript我有一个对象数组,每个对象都有一个图像网址。我想删除图像网址被破坏的对象(返回404)。
到目前为止我的代码,其中items是一个对象数组:
function rmBadImageCheck (items){
console.log("doing image checks");
var x = items.length;
for (var i = 0; i < x; i++) {
var img = new Image()
img.src = items[i].image_url;
img.onerror = function(){
console.log("need to splice at: " + i)
items.splice(i, 1)
}
}
console.log(items);
return items;
}
但是由于img.onerror是异步的,所以循环在剪接被调用时完成。如何从阵列中删除包含错误的图像。
答案 0 :(得分:1)
这将链接检查(不会检查项目,直到检查前一项目)。检查所有元素后,使用新项作为参数调用回调函数。
var index = 0;
function rmBadImageCheck (items, callback){
var x = items.length;
//if all items have been checked, terminate the chain (by returning) and call the callback with the new items
if(index >= x)
return callback(items);
var img = new Image();
img.src = items[index].image_url;
// if error, splice the item from the array, and check the next one which will be on the same index because of the splice call (that's why we don't increment index)
img.onerror = function(){
items.splice(index, 1);
rmBadImageCheck(items, callback);
}
// if success, keep the item but increment index to point to the next item and check it
img.onload = function(){
index++;
rmBadImageCheck(items, callback);
}
}
var items = [/*...*/];
// when calling rmBadImageCheck pass a callback function that accept one argument (the newItems array).
rmBadImageCheck(items, function(newItems){
// use that array here
console.log(newItems);
});
如果要在许多阵列上应用函数rmBadImageCheck
,则每次都应将index
重新初始化为0
。