找不到未定错误的属性长度

Cannot find property length of undfined error

本文关键字:属性 错误 找不到      更新时间:2023-09-26

我使用以下代码,当我有结果时它工作正常,但如果我不是有错误吗,在javascript中有一种方法可以在一行代码中避免它,或者我必须将其传播两行?如果我必须如何推荐>

   if( oData[aProp[0].split('/')[0]].results.length > 0){
     ....
好吧,

你可以用一行来做到这一点:

if( oData[aProp[0].split('/')[0]].results
    && oData[aProp[0].split('/')[0]].results.length > 0){
}

但这效率低下,因为您要进行两次拆分,并且看起来有点混乱。

先创建一个变量更好、更容易阅读:

var oDataEntry = oData[aProp[0].split('/')[0]];
if( oDataEntry.results && oDataEntry.results.length > 0){
}
var tempArr = null;
var tempAProp = null;
var tempLength = (tempAProp = aProp[0]) && ( tempArr= oData[tempAProp.split('/')[0]]) ?  tempArr.length:0;
if( tempLength > 0){
}