I would like to find a way to programmatically (i.e. by writing code) find for what values of x
we have the express开发者_Go百科ion x == null
evaluating to true
.
It is impossible to (without prior knowledge of at least the basic JavaScript rules) be able to programmatically determine all values of x
for which x == null
is true. However, the following should show a pattern from which a heuristic can be derived:
var v = [null, undefined, false, true, -1, 0, 1, "", " ", "0", {}, []]
for (var i = 0; i < v.length; i++) {
var x = v[i]
alert(x + " == null? " + (x == null))
}
(This particular test case does cover all the times when it would be true.)
Similar tests can be done for == false
, etc.
Happy coding.
See Ray Toal's answer for more suggestions of test values.
In the absence of knowing at least something about how JavaScript performs type conversions the way these conversions are applied over the operator ==
you would have to test every possible value against null
, and the number of possible values are unlimited, so what you ask cannot be done.
With a little bit of knowledge you can break down the world of all possible JavaScript expressions into the following categories:
- undefined
- null
- true
- false
- 0
- negative finite numbers
- positive finite numbers
- negative infinity
- positive infinity
- NaN
- empty string
- a string full of whitespace
- a string with at least one non whitespace character
- an empty object
- an object with some properties
Test a representative value from each class against null
and see what you get.
I assume from the way the question was phrased that you know the exact section in the ECMA-262 specification that defines, precisely, the semantics of ==
. ( Section 11.9.3 of the 5.1
spec )
精彩评论