可以忽略无法读取未定义的属性'0'? [英] Possible to ignore Cannot read property '0' of undefined?
本文介绍了可以忽略无法读取未定义的属性'0'?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在创建一个个人脚本,在某些情况下会收到错误:
I am creating a personal script that in some instances gets the error:
Cannot read property '0' of undefined
我有类似的东西
item["OfferSummary"][0]["LowestUsedPrice"][0]["FormattedPrice"]
是否可以完全忽略/覆盖此错误,以便它只打印n / a或 - 在那种情况下?
Is it possible to completely ignore/override this error so that it just prints n/a or -- in that scenario?
推荐答案
您可以使用样板函数来执行此操作:
You can use a boilerplate function to do so:
function get(obj, property) {
if (Array.isArray(property)) {
var current = obj;
for (var i = 0, l = property.length; i < l; ++i) {
if (Object(current) === current) current = current[property[i]];
else {
current = undefined;
break;
}
}
return current;
}
if (Object(obj) === obj) return obj[property];
}
将字符串或数组传递给 get
查找属性 - 如果找不到,将返回 undefined
。
Pass either a string or an array to get
to find the property -- if not found, undefined
will be returned.
示例:
get(window, ['location', 'href']); // "http://stackoverflow.com..."
get(Number, 'MAX_VALUE'); // 1.7976931348623157e+308
这篇关于可以忽略无法读取未定义的属性'0'?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文