user4261401
user4261401

Reputation:

Cannot find property length of undfined error

I use the following code that when I've results Its working ok but if isnt I got error , There is a way in javascript to avoid it in one line of code or I must spread it for two lines? if I must how its recomended >

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

     ....

Upvotes: 2

Views: 74

Answers (2)

RIYAJ KHAN
RIYAJ KHAN

Reputation: 15292

var tempArr = null;
var tempAProp = null;
var tempLength = (tempAProp = aProp[0]) && ( tempArr= oData[tempAProp.split('/')[0]]) ?  tempArr.length:0;

if( tempLength > 0){
}

Upvotes: 1

Rhumborl
Rhumborl

Reputation: 16609

Well you can do it in one line with:

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

but this is inefficient because you are doing the split twice, and looks a bit messy.

It is better and easier to read to create a variable first:

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

Upvotes: 4

Related Questions