aletat aletat - 1 month ago 6
Node.js Question

node.js: get variable's name

let f = function(list) //'list' is an array [o1, o2, etc.]
{
list.forEach(function(e)
{
console.log('name ', ??);
};
};


just wonder how to get current elm's name to have output like that:
o1
o2

thnx

p.s. toString() puts [object Object]

Answer

Referencing forEach here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

Doing a forEach you get access (in the callback) to three pieces of information. The currentValue, the index and the whole array. I'm unsure exactly of what you are looking for, but given that it is an array you really only have 2 key pieces, the index and the value.

Changing your code up you can output both of those pieces of data like this:

let f = function(list) { //'list' is an array [o1, o2, etc.]
    list.forEach(function(val, ind) {
        console.log('value at index(%d): %o', ind, val)
     })
}

Note that I use %o for the value as it is the best catch-all for handling multiple different types of objects when using console.

Comments