javascript - 另一个 Javascript 未定义空问题

标签 javascript null undefined

所以我已经回答了这里的大部分问题。还有不少文章好坏参半。

我正在寻找一些额外说明的一件事是如何处理未定义和未声明的变量。

获取下面的代码。

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 函数是否递归地执行某些操作来评估引发运行时错误的子属性?

  1. 我想这里的实际问题是,如果我检查 a.c 中的嵌套对象 c,如果 a 未定义,我可以立即假设 c 未定义?

  2. 如果我想检查一些极度嵌套的对象以查看它是否像 MyObject.Something.Something.Something.x 中的 x 那样设置,那么最好的方法是什么?我必须逐个元素地浏览结构,确保每个元素都存在,然后再转到链中的下一个元素?

最佳答案

I can immediately assume c is undefined if a is undefined?

是的。

I have to navigate through the structure element by element making sure each one exists before going to the next one down in the chanin?

是的。

关于javascript - 另一个 Javascript 未定义空问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1828130/

相关文章:

mysql left join - 使用 NULL 和条件返回行

reporting-services - 如何用单词替换SSRS中的NULL值?

javascript - 什么时候在 JavaScript 中使用 null 或 undefined?

javascript - 防止 javascript 加载多次

javascript - 如何捕捉 "Maximum call stack size exceeded"错误?

javascript - 解决所有错误后,如何使 data-parsley-errors-container ="#element"消失?

constructor - 从Dart中的工厂构造函数返回null是否可以接受?

javascript - 如果我们设置未定义的值会发生什么?

php - Laravel 4:PHP fatal error :调用未定义的方法 Blueprint::int()

javascript - 带缩略图的产品图片库