-1

in javascript i am trying to check if a "key" has been defined on an array, and if it doesn't create it and assign a value 0 to it.

the following code is part of a large script and it is inside some loops that change the value of project, country and month

console.log(typeof total_searches[project][country][month]);
if(typeof total_searches[project][country][month] !== "number");
    total_searches[project][country][month] = 0;

but for some reason, when it goes over this 'if' for the second time (all the keys are defined by then) it evaluates as TRUE and assigns 0 to it.

The console.log shows "number" when doing a debug using chrome.

i also tried if(!(month in total_searches[project][country]))

but it still evaluates to TRUE and goes in

what am i doing wrong?

thanks

1
  • So in log, it is a number and in the if clause it isn't? Commented Aug 10, 2011 at 16:40

3 Answers 3

5

You got a nasty sneaky semicolon after the if.

if(typeof total_searches[project][country][month] !== "number"); // <-- here
Sign up to request clarification or add additional context in comments.

Comments

1

!== also does a type match as well. try just !=

Comments

1

You have a semicolon after your if-statement, which is seen as the true-statement. So the next line is always executed as it is seen as 'just' another line of code.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.