gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 16:39:21 26 4
gpt4 key购买 nike

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

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

获取下面的代码。

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com