简体   繁体   中英

Shorthand for “console.log(”var: “ + var)”?

It would be nice to have a super quick way to do this:

"console.log("var: " + var)"?

Tried this, but not sure if there's a way to get a variable name as a string once it's been passed in, or convert the name string to a reference to the variable...

var mLog = function(varNameStr){
   console.log(varNameStr + ": " + _____);
}

EDIT: Judging by the results of googling "get name string of a variable js", it looks like there's no easy way to grab the name string of a variable from the reference (You have to create hash tables or other structures that make it not worthwhile.)

So, the only possible solution would be to convert a string into a reference to the variable. Is that possible in JS?

The following will do the trick. Pass it a variable name in string form.

var mLog = function(varStr){
  console.log(varStr + ": " + eval(varStr));
}

Example:

> var strVar = 'A string variable';
> mLog('strVar');
< strVar: A string variable

> var arrVar = [1,2,3];
> mLog('arrVar');
< arrVar: 1,2,3

There is no way to "extract" the variable name, since variables aren't actually data. The closest thing you could do is use it for objects. Something like:

var obj= {
        prop: 'value'
    };

function mLog(object, prop) {
  console.log(prop + ': ' + object[prop];
}

mLog(obj, 'prop');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM