开发者

Javascript / jQuery + length = problem

开发者 https://www.devze.com 2023-03-31 12:38 出处:网络
A small version of my script would be this: var x = null; for(var i=0; i<x.length; i++) { //do stuff } I noticed (by doing some \'alert\' debugs) that my script halts when evaluating x.length. E

A small version of my script would be this:

var x = null;
for(var i=0; i<x.length; i++)
{
    //do stuff
}

I noticed (by doing some 'alert' debugs) that my script halts when evaluating x.length. Even when i try to print it in an alert, the script stops.

The idea is that some开发者_如何学Cthimes my x variable is an array, sometimes is null.

Of course, I am a beginner, so probably i've done something stupid. No errors appear in my Firefox 6 error console.

Thanks a lot for any ideas!


try

var x = null;
for(var i = 0; x && i < x.length; i++) {
    //do stuff
}

This will first check whether x is not null. If x is null, for will not run. If it is not null, for will run as usual.


In your code x is null and you are trying to get the length property from a null value which will throw a javascript error. Please check your console you will definitely see an error.

In such situations you should always make sure you do null check before accessing any property of the object or variable. Try this

var x = null;
if(x){
   for(var i=0; i<x.length; i++)
   {
      //do stuff
   }
}


That's because it's null. Add this if statement

if (x !== null){
    for(var i=0; i<x.length; i++)
    {
        //do stuff
    }
}

and it should be fine.


var x = null;

if(x !== null){
    for(var i=0; i<x.length; i++)
    {

        //do stuff
    }
}

Seems to fix the problem


Why don't you initialize x with var x = [];? This way, you can make sure that it is always an array, yet the loop won't do anything if it's empty.


You can't call the method length on a null object. So you need to test if the object is null before calling it.

var x = null;
if(x != null)
{
  for(var i=0; x!= null && i < x.length; i++)
  {
     //do stuff
  }
}

or

var x = null;
for(var i=0;x!= null && i<x.length; i++)
{
   //do stuff
}


Another option here would be to initialize x to an object with the length property -

x = {
      length : 0
    };

instead of

x = null;

EDIT : pulsar's answer makes more sense!

0

精彩评论

暂无评论...
验证码 换一张
取 消