JS / Lodash / Nodejs:在lodash foreach循环中,正在迭代的variables的打印名称

我有以下循环结构迭代对象引用数组,为每个定义的对象做一些事情,并应打印出未定义对象的名称。

为此,我需要打印传入迭代器的实际对象名称。

有没有提供传递给迭代函数的参数的名称的运算符?

//couple of objects with some data var a = { .... }; var b = { .... }; //undefined object var c; var d; var e; . . . . var someNthVar; _.forEach ( [a,b,c,d,e,....], function (obj) { if (obj) { //do something } else { //PROBLEM!!! How do i specify that variable 'c' is the one that is undefined //log undefined variables console.log('Undefined variable: ' + obj.variableName); } } ); 

有没有提供传递给迭代函数的参数的名称的运算符?

不可以。您可以定义一个名称列表,然后通过索引关联它们:

 const names = ['a', 'b', 'c']; [a, b, c].forEach((obj, i) => { if (!obj) { throw new Error(`${names[i]} missing a value`); } // do something }); 

你有没有考虑过使用JavaScript对象来保存你的值?

这样你可以写下类似的东西,使用类似的forIn ;

 var objects = { a: {...}, b: {...}, c: undefined, d: {...} } _.forIn(objects, function(value, name){ if (!value) { throw new Error(`${name} is missing a value`); } // Do something });