[英]JS/Lodash/Nodejs: Printing name of variable being iterated upon within lodash foreach loop
我有以下循環結構,該結構遍歷對象引用數組,對每個定義的對象執行某些操作,並應打印出未定義對象的名稱。
為此,我需要打印傳遞給迭代器的實際對象名稱。
是否有任何運算符提供傳遞給iteratee函數的參數的名稱?
//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);
}
}
);
是否有任何運算符提供傳遞給iteratee函數的參數的名稱?
否。您可以定義一個名稱列表,並通過索引將它們關聯,但是:
const names = ['a', 'b', 'c'];
[a, b, c].forEach((obj, i) => {
if (!obj) {
throw new Error(`${names[i]} missing a value`);
}
// do something
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.