javascript - 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 语句?
解决方案
首先是坏消息,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
,尽管绕过这很容易。
推荐阅读
- ms-access - MS Access - 使用“按表单过滤”时更改表单的外观
- r - 来自 Antidote(法语词典)软件的 R 控制台中的重复消息
- java - 如何限制 ScrollPane 的滚动量
- qt - 使用 Qt 和 QML 为我的错误解释调试器输出
- javascript - ThreeJS:当在另一个网格中时,网格变得不可见
- python - python docx找不到docx文件
- visual-studio - Visual Studio 2017 构建解决方案失败
- sql - SQL 按不相关的日期连接两个表
- javascript - 上传绘画失败:文章必须存在 - opoloo
- ios - iOS 推送通知的 AWS SNS 声音未发生