【发布时间】:2019-11-14 12:00:49
【问题描述】:
我正在像这样检查null:
假设c 为空。
if (a == null || b == null || c == null || d == null) { //short cirtcuit on the first null value (c)
let grabNullKey = a == null || b == null || c == null || d == null;
// I want this to grab the variable that is null, instead this logs `true`
console.log(grabNullKey)
我想将变量名 (c) 记录给用户,是否有一种简写方式来输出变量名而不是执行 4 个 if 语句?
【问题讨论】:
-
你为什么要记录变量名?
-
@adiga yes output
c变量名,有问题更新 -
但是,你为什么需要这个?我的意思是,可以使用 if-else 链或使用简写属性名称来做到这一点。
-
@adiga 是的,所以我知道我可以对
console.log变量名执行一大块 if-else 语句(或 switch 语句)。但是如果要检查的条件很长,它将需要很大的 if-else 块,并且由于我们已经在为 null 的变量上短路,我希望有一种快速的方法可以将变量名输出到日志。记录此信息将很有用,因此当条件中断时,调试起来会快得多。 -
const obj = { a, b, c, d }; const key = Object.keys(obj).find(k => obj[k] === null)这样的东西应该可以工作。
标签: javascript short-circuiting