简体   繁体   中英

typeof result of 2 undefined variable

I just test the "typeof" in javascript, and really don't know why the result is like this.

/ * ** * /

var cota,
    plouto;

alert(typeof plouto/cota); //NaN 

/ * ** * /

var cota,
    plouto;

alert(typeof (plouto/cota)); //number

/ * ** * /

var cota,
    plouto;

var flo = plouto/cota;

alert(typeof flo); //number 

The first one alerts NaN because the typeof plouto is executed first, and the result is divided by cota . The result of that is not a number, hence NaN . You could imagine it like this:

(typeof plouto) / cota

The second one divides plouto by cota , which is not a number (because both variables are undefined ), but the type of NaN is actually Number , which can be confusing!

The same goes for the third example.

The typeof operator has precedence over the math operators, so it's executed first.

What you get from typeof plouto/cota is first typeof plouto then the return value divided with cota - resulting in Not A Number. When doing math operation and one of the "participants" is not a number, the whole result will also be NaN.

The other two cases are more simple: the type of NaN is number. Think of that as the equivalent of null for objects.

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