gpt4 book ai didi

javascript - 这种做法叫什么? `objectName && objectName.thing`

转载 作者:行者123 更新时间:2023-12-03 04:33:22 25 4
gpt4 key购买 nike

我正在尝试查找实践的名称(以任何语言),在该实践中,在执行查找之前检查对象是否存在。通常这是通过在对象和对象查找表达式之间添加 && 来完成的,就像在 JS 中一样:

var example = objectName && objectName.thing;

这样 example 会被评估为 undefinedobjectName.thing,并避免运行时错误。

我可以发誓我以前听过这个,但我完全忘记了。这种做法叫什么?

最佳答案

这有时被称为“守卫”,因为左操作数的真实性守卫对右操作数的访问。当然,这只是一个逻辑 AND,但在此特定上下文中使用 AND 有时被称为“防护”。

来自 Douglas Crockford 的 A Survey of the JavaScript Programming Language :

The && operator is commonly called logical and. It can also be called guard.

来自Guard and Default Operators of JavaScript作者:肖恩·麦克阿瑟:

In Javascript, the way the languages determines logical operations and the values Javascript treats as true or false lead to people using the AND and OR operators for guard and default situations

关于javascript - 这种做法叫什么? `objectName && objectName.thing`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43398734/

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