深度 Javascript 检查是否未定义且没有 TypeError
我厌倦了写类似的东西
if (
typeof Foo != 'undefined' &&
typeof Foo.bar != 'undefined' &&
typeof Foo.bar.baz != 'undefined' &&
Foo.bar.baz == 'qux'
) {...}
在 PHP 中它会好一点:
if (!empty($foo['bar']['baz']) && $foo['bar']['baz'] == 'qux') {...}
理想情况下会是:
function u(value) {
return (typeof value != 'undefined') ? value:null;
}
if (u(Foo.bar.baz) == 'qux') {...}
但当我尝试这样做时,浏览器显示“TypeError”。有什么办法可以让“u”发挥作用吗?
I'm tired to write something like
if (
typeof Foo != 'undefined' &&
typeof Foo.bar != 'undefined' &&
typeof Foo.bar.baz != 'undefined' &&
Foo.bar.baz == 'qux'
) {...}
In PHP it's a little bit better:
if (!empty($foo['bar']['baz']) && $foo['bar']['baz'] == 'qux') {...}
Ideally it would be:
function u(value) {
return (typeof value != 'undefined') ? value:null;
}
if (u(Foo.bar.baz) == 'qux') {...}
But browser shows "TypeError" when I try to do this. Is there any way to make "u" function?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
2020 年 4 月更新
从 Node.JS 版本 14 开始,您现在可以使用以下语法进行“可选链接”
如果任何链接属性不存在,则值将被键入“未定义”。
https://v8.dev/features/optical-chaining
原始回复:
您不必明确声明未定义。检查可以是这样的:
或者你可以有一个 try catch 块来捕获是否有任何错误:
但是是的,我可以看到问题。我建议尝试避免像您一样的深层嵌套。
April 2020 Update
As of Node.JS version 14, you can now use the following syntax for "optional chaining"
If any of the chained properties don't exist, then the value will be typed "undefined".
https://v8.dev/features/optional-chaining
Original reply:
You don't have to state the undefined explicitly. The check can be something like:
Or you can have a try catch block to catch if there is any error:
But yes I can see the problem. I would suggest to try and avoid deep nesting like you have.
为了解决这个问题,我使用 Lodash _.get。
如果
Foo.bar
或Foo.bar.baz
未定义,您将不会收到类型错误,并且更容易阅读和调试。To solve this problem I use Lodash _.get.
If
Foo.bar
orFoo.bar.baz
are undefined, you will not get a type error, and it's quite a bit easier to read and debug.JavaScript 中有一个新的可选链运算符。截至 2020 年,它仅适用于最新版本的流行浏览器。所以我建议仅将其与转译器一起使用。
There is a new optional chaining operator in JavaScript. As of 2020 it is working only in the newest version of the popular browsers. So I recommend using it only with transpilers.
当你假设链中的每个步骤都是一个对象而不是 0、“” 或布尔值 false 时,你可以这样写:
但毕竟最好不要有这么深的嵌套对象
As you assume that every steps in your chain is an object and not 0, "" or boolean false you can write:
But after all its better not to have such deep nested objects