Reputation: 467
A couple days ago, on a site that I'm the only author on, I added this code to a script:
if (PowerArray[0][0].length < 1);
{
return false;
}
and everything worked fine. When PowerArray[0][0] was "70", the script ran. When PowerArray was empty, the script didn't run past the above quoted line. This is no longer true. For the life of me, I can't figure it out. I tested with variants of the code, like below:
if (PowerArray[0][0].length < 1);
{
alert(PowerArray[0][0].length);
return false;
}
and set PowerArray[0][0] = "70". When I run the code, I get an alert with "2" in the text. This is the only place that I have an alert in the script. What's going on here, and how do I fix it?
Note: The expected behavior is, of course, no alert, because "70" has a length of 2, and shouldn't trigger the truth of the if.
Edit: 1) Yes, the False
in the first block was a typo. It's been corrected. 2) The expected behavior was for it to stop processing if (and only if) PowerArray[0][0].length was 0. 3) I had previously initialized PowerArray as an empty array, and then copied an array (which had the potential to be empty) into it.
Upvotes: 0
Views: 132
Reputation: 3866
You should remove semicolon from if statement, it terminates your statement there. And yes, when your PowerArray is empty, PowerArray[0][0] will throw an undefined error, So should put a null check for that as well.
Upvotes: 4
Reputation: 388316
when PowerArray
is empty PowerArray[0]
gives undefined then you will get an error for PowerArray[0][0]
saying TypeError: Cannot read property '0' of undefined
that is why the script is nor running after that line
if (PowerArray && PowerArray[0] && PowerArray[0][0] && PowerArray[0][0].length < 1)
{
return false;
}
Upvotes: 3
Reputation: 23801
try this
if (PowerArray[0]) {
if (PowerArray[0][0].length < 1) {
return False;
}
}
Upvotes: 0
Reputation: 39248
I think the semicolon after the if is the issue. I would also check if PowerArray is a valid 2D array implementation. Check this link for ideas How can I create a two dimensional array in JavaScript?
Start by changing it to this if (PowerArray[0][0].length < 1)
Upvotes: 0