这种做法叫什么? `objectName && objectName.thing`
What is this practice called? `objectName && objectName.thing`
我正在尝试查找在执行查找之前检查对象是否存在的实践名称(任何语言)。通常这是通过在对象和对象查找表达式之间插入一个 &&
来完成的,就像在 JS 中一样:
var example = objectName && objectName.thing;
这样 example
被评估为 undefined
或 objectName.thing
,并避免运行时错误。
我发誓我以前听过这个,但我完全忘记了。这种做法叫什么?
这有时称为 "guard,",因为左操作数的真实性 guards 对右操作数的访问。当然,它只是一个逻辑与,但在这个特定的上下文中使用 AND 有时被称为 "guard".
来自道格拉斯·克罗克福德的 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
这种做法有时称为验证或评估。您可以使用 三元运算符 来做到这一点。
var example = objectName ? objectName.thing : null
这将根据 objectExample
将 objectName.thing
或 null
分配给 example
我正在尝试查找在执行查找之前检查对象是否存在的实践名称(任何语言)。通常这是通过在对象和对象查找表达式之间插入一个 &&
来完成的,就像在 JS 中一样:
var example = objectName && objectName.thing;
这样 example
被评估为 undefined
或 objectName.thing
,并避免运行时错误。
我发誓我以前听过这个,但我完全忘记了。这种做法叫什么?
这有时称为 "guard,",因为左操作数的真实性 guards 对右操作数的访问。当然,它只是一个逻辑与,但在这个特定的上下文中使用 AND 有时被称为 "guard".
来自道格拉斯·克罗克福德的 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
这种做法有时称为验证或评估。您可以使用 三元运算符 来做到这一点。
var example = objectName ? objectName.thing : null
这将根据 objectExample
将objectName.thing
或 null
分配给 example