简体   繁体   中英

Checking for undefined causes undefined error

Trying to check if some variables contain things, because they throw errors and break the ajax function when they don't. Problem is that just checking if data[2][0] contains something causes the following error:

Uncaught TypeError: Cannot read property '0' of undefined

I'd very much prefer not to check this in a previous stage. How do I check if data[2][0] is defined, without causing the actual checking to break my js?

Code:

//ajax ^
success: function(data){
    var xp = data[0][0]; //Contains a string
    var yp = data[1][0]; //Contains a string
    var zp = data[2][0]; //Is not set, fails here

    if(xp === ''){ //Tried using null & undefined here aswell
       //Do nothing   
    } else {
        var one = data[0][0];
        var oneH = data[0][1];
        var oneS = data[0][2];
    }
    if(yp === ''){
        //Do nothing
    } else {
        var two = data[1][0];
        var twoH = data[1][1];
        var twoS = data[1][2];
    }
    if(zp === ''){
        //Do nothing  
    } else {
        var three = data[2][0];
        var threeH = data[2][1];
        var threeS = data[2][2];
    }
//ajax continues v

Any help will be much appreciated.

You should check if a variable is undefined using typeof , not with an equality check against '' :

if (typeof myVar === 'undefined')

You can also check if a variable is an array using Array.isArray(myVar)

I would check to see if data[2] exists first, and then redefine zp if it does.

var zp = data[2];
if (zp) zp = zp[0];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM