首页 > 解决方案 > Javascript获取短路变量名称

问题描述

我正在检查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 语句?

标签: javascriptshort-circuiting

解决方案


首先是坏消息,JavaScript 不允许您将变量名打印为字符串。好消息是有办法解决它。

为了能够打印变量名称,您将需要使用一个对象而不是一系列变量。所以你需要一个像这样的对象:

const variableObject = { a: true, b: true, c: null, d: true };

要找到第一个空值并打印它,您需要遍历它们的键并找到第一个为空的:

const variableObject = { a: true, b: true, c: null, d: true };
const variableNames = Object.keys(variableObject); // ['a', 'b', 'c', 'd']
const firstNullVar = variableNames.find((key) => variablesObject[key] === null); // 'c'
console.log(firstNullVar); // will print the string 'c'

如果没有任何变量是null,这将打印undefined,尽管绕过这很容易。


推荐阅读