所以我已经解决了这里的大部分问题。也有不少文章有好有坏。
我正在寻找一些额外说明的一件事是如何处理未定义和未声明的变量。
拿下面的代码。
var a;
if(a == null) // True - Due to Type Coercion
if(a == 'null') // False
if(a === null) // False
if(a === 'null') // False
if(a == undefined) // True
if(a === undefined) // True
if(a == 'undefined') // False
if(a === 'undefined') // False
if(a) // False - A is undefined
alert(typeof(a)) // undefined
以上我都明白了。但是当您查看未声明的变量时,事情会变得很奇怪。请注意,我特别省略了“var b;”。
alert(typeof(b)) // undefined
if(typeof(b) == 'undefined') // True
if(typeof(b) === 'undefined') // True - This tells me the function typeof is returning a string value
if(typeof(b) == 'null') // False
if(typeof(b) === 'null') // False
if(typeof(b) == null) // False
if(typeof(b) === null) // False
if(b) // Runtime Error - B is undefined
typeof(b) 之后的任何其他操作都会导致运行时错误。我仍然可以理解语言评估表达式的方式背后的逻辑。
所以现在我看到 a 的一个不存在的属性,我真的很困惑。
if(a.c) // Runtime Error - c is null or not an object
alert(typeof(a.c)) // Runtime Error - undefined is null or not an object
我认为在这种情况下 c 将被视为 b 在前面的示例中,但事实并非如此。您必须将 a 实际初始化为某些东西,然后才能使其表现得像 b 一样。并阻止它抛出运行时错误。
为什么会这样?是否对未定义类型进行了一些特殊处理,或者 typeof 函数是否递归地执行某些操作来评估引发运行时错误的子属性?
我想这里的实际问题是,如果我在 ac 中检查嵌套对象 c,我可以立即假设 c 未定义,如果 a 未定义?
如果我想检查一些极其嵌套的对象以查看它是否设置为 MyObject.Something.Something.Something.x 中的 x ,那么最好的方法是什么?我必须逐个元素地浏览结构元素,确保每个元素都存在,然后再转到链中的下一个元素?