javascript undefined check not working
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 evaluate开发者_如何学Cs 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
You got a nasty sneaky semicolon after the if
.
if(typeof total_searches[project][country][month] !== "number"); // <-- here
!== also does a type match as well. try just !=
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.
精彩评论