undefinedfix
Sign in

How does JS get the variable name of the variable itself through a variable?

lfkeg edited in Fri, 29 Jul 2022

For example: let a = 123; how can I get the variable name 'a' corresponding to variable a? Note: a here can be of any type. The effect I want to achieve is to quickly add a prefix to the log, such as printing a shoppinglist object

mylog(shoppinglist);

The final results are as follows:

clipboard.png

This makes it easy to view logs and search.

3 Replies
theeranitp
commented on Fri, 29 Jul 2022

Using a syntax of ES6 should meet your needs

var shoppinglist = {"沐浴露":1, "洗衣粉":3};
console.log({shoppinglist});
LiuGN
commented on Fri, 29 Jul 2022

I don't think so , But you can write it upside down , as

function mylog(str){
  console.log(str+'='+ eval(str));
}

let a=1;
mylog('a');

Will output

a=1
Chuck
commented on Fri, 29 Jul 2022
var shoppinglist = {"沐浴露":1, "洗衣粉":3}
console.log(Object.keys({shoppinglist})[0])  // shoppinglist

However, it can not be encapsulated as a function, because in the process of parameter passing, the value of the variable is passed instead of the variable name.