《eloquent javascript》 notes1

2017-08-08  本文已影响8人  nummycode

value, types and operator

There is only one value in JavaScript that is not equal to itself, and that is NaN, which stands for “not a number”.

console.log(NaN == NaN)
// → false

When something that doesn’t map to a number in an obvious way (such as "five" or undefined) is converted to a number, the value NaN is produced. Further arithmetic operations on NaN keep producing NaN.

When comparing values of the same type using ==, the outcome is easy to predict: you should get true when both values are the same, except in the case of NaN.But when the types differ, JavaScript uses a complicated and confusing set of rules to determine what to do. In most cases, it just tries to convert one of the values to the other value’s type. However, when null or undefined occurs on either side of the operator, it produces true only if both sides are one of null or undefined.

console.log(null == undefined);
// → true
console.log(null == 0);
// → false

That last piece of behavior is often useful. When you want to test whether a value has a real value instead of null or undefined, you can simply compare it to null with the == (or !=) operator.

The rules for converting strings and numbers to Boolean values state that 0, NaN, and the empty string ("") count as false, while all the other values count as true. Because of this, expressions like 0 == false and "" == false are also true.

data strcuture

Almost all JavaScript values have properties. The exceptions are null and undefined. If you try to access a property on one of these nonvalues, you get an error.

null.length;
// → TypeError: Cannot read property 'length' of null

the document object

Unlike methods such as getElementsByTagName, the object returned by querySelectorAll is not live. It won’t change when you change the document.

The querySelector method (without the All part) works in a similar way. This one is useful if you want a specific, single element. It will return only the first matching element or null if no elements match.

上一篇 下一篇

猜你喜欢

热点阅读