aletat aletat - 1 year ago 74
Node.js Question

node.js: get variable's name

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

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


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

Answer Source

Referencing forEach here:

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download