[英]Javascript check if array filled from function
我有这个功能
offer.getReceivedItems(function(err, items) {
它返回一个数组(项目),或者如果失败则抛出错误err
。 很多时候,当没有err
,items数组为空。 喜欢
[]
但是当此数组为空时,我需要再次尝试相同的功能
offer.getReceivedItems(function(err, items) {
但是当物品为空时,我该如何返回到它...
我做了很多尝试,但是找不到...
代码看起来像
offer.getReceivedItems(function(err, items) {
if (err) {
console.log("Couldn't get received items: " + err);
offer.decline();
} else {
console.log(items);
items.forEach(function(item,i,arr){
....
当有一个空数组时, forEach
不会运行。
在使用forEach
迭代之前,应检查数组是否为空。 检查items.length
。
这个StackOverflow答案中有更长,更详细的解释。
我无法理解您要做什么,但是以下内容对您有帮助吗?
var callBack = function(err, items) {
if (err) {
console.log("Couldn't get received items: " + err);
offer.decline();
offer.getReceivedItems(callBack); // Call again
} else {
console.log(items);
items.forEach(function(item,i,arr){
....
}
};
// Original call
offer.getReceivedItems(callBack);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.