给定 array/list 个变量名,如果变量为空,则将所有变量名打印为字符串

Given an array/list of variable names, print all the variable names as string if the variable is null

除了拥有许多 if...else 函数并将变量名称硬编码为字符串之外,还有什么简单的方法。 假设我们有 10 个变量,它们可能包含也可能不包含某些值。我希望能够 return 列出所有那些为空的变量名。

而不是做:

if (x == null) return "x"

对于所有变量,有没有更好的方法可以做到这一点?正在寻找 javascript/jquery 或下划线方法。

您无法凭空获得变量列表,因此您需要测试对象的属性。

这应该适用于对象。它获取所有键并通过 isNUll

过滤它们
console.log(_.filter(_.keys(object),(key)=>{
    return _.isNull(object[key]);
}));

您可以阅读更多关于获得当前范围变量的不可能(或非常不可能)的信息:Getting All Variables In Scope

如果您在评论中遵循@Pointy 的建议并将您的变量属性设为对象,您将能够执行以下操作:

const person = {
    firstName: "John",
    lastName: null,
    age: null
}

for(let prop in person) {
    if(person[prop] === null)  console.log(prop + ' is null');
}

而且如果你想检查一些全局声明的变量的值,它不会比多个 ifs 更简洁但更优雅:

['x', 'y', 'z'].map((propName) => {
    if(window[propName] === null || window[propName] === undefined) 
        console.log(prop + ' is not defined');
});

你应该像这样维护一个变量的对象x,y(例如在 ES6 中)

var obj = {
  x,
  y
}

然后过滤掉空属性

Object.keys(obj).filter(k => obj[k] === null)

将返回空变量名称数组。