I want to create a quick function that will console.log
a variable name and the value. I'd like the result of the function to show in the console: foo: bar
.
My basic idea for the function looks like this:
function varlog(var_name)
{
console.log(var_name + ": " + eval(var_name));
}
And I'd call is thusly:
function someRandomFunction()
{
var foo = "bar";
// ... some stuff happens
varlog("foo");
}
This works if foo
is global, but doesn't work in the example provided. Another option that also only works globally is using window[var_name]
instead of the scary eval
.
I don't think what I'm asking is possible, but I figured I'd throw it out there.
I'm spending a lot of time attempting to be lazy. My current method is just console.log('foo: ' + bar);
which works just fine. But now I just want to know if this is possible.
Some other questions I referenced in searching for this / creating what I have now:
- Variable name as a string in Javascript
- How to convert variable name 开发者_StackOverflow中文版to string in JavaScript?
- Javascript, refer to a variable using a string containing its name?
- How to find JavaScript variable by its name
--
Edit: I'd love to just call varlog(foo)
, if the name "foo" can be derived from the variable.
Solution - (for your actual use case) - console.log({foo})
In ES6 IdentifierReference
s are being accepted as PropertyDefinition
s on the ObjectLiteral
's PropertyDefinitionList
(see compatibility chart):
The variable name is being set to the Object
's Property
's key
and the variable value is being set to the Object
's Property
's value
.
As console.log
shows Object
s with their Propertiy
/ies' key
s and value
s you can use that to see both your variable's name and value by invoking console.log({foo})
.
Note that when you initialize a single anonymous
object
with several variables as I did in the secondconsole.log
while they appear in the same order as initialized here in the snippet's output they might get reordered (alphabetically) elsewhere.
var testint = 3
var teststring = "hi"
var testarr = ["one", 2, (function three(){})]
var testobj = {4:"four", 5:"five", nested:{6:"six",7:"seven"}}
console.log({testint})
console.log({testint, teststring, testarr, testobj})
Answer - (to the question title) - Object.keys({foo})[0]
You can also use this shorthand Object Initializer
together with Object.keys()
to straightly access the variable name:
var name = "value"
console.log(Object.keys({name})[0])
The reason it doesn't work is because the variable foo
is not accessable to the function varlog
! foo
is declared in someRandomFunction, and is never passed into varlog
, so varlog
has no idea what the variable foo is! You can solve this problem by passing the variable foo
into the function(or using some sort of closure to make foo
in the scope of varlog
) along with its string representation, but otherwise, I think you are out of luck.
Hope this helps.
While I'm not aware of such a possibility, I'd wanted to share a small idea:
Object.prototype.log = function(with_message) {
console.log(with_message + ":" + this);
}
var x = "string";
x.log("x");
Like I said, a small idea.
Kind of combining a couple of anwers into a small function
Would this work for you?
const log = function() {
const key = Object.keys(this)[0];
const value = this[key];
console.log(`${key}: ${value}`);
}
let someValue = 2;
log.call({someVlaue}); //someValue: 2
Works with function too, even itself.
log.call({log});
// It would return the following
log:function() {
const key = Object.keys(this)[0];
const value = this[key];
console.log(`${key}: ${value}`);
}
I don't believe what you want to do is possible.
The best alternative I can think of is to pass an object to varlog
that is basically a key-value hash:
function varlog(obj)
{
for (var varname in obj) {
console.log(varname + ": " + obj[varname]);
}
}
function someRandomFunction()
{
var foo = "bar";
// ... some stuff happens
varlog({foo: foo});
}
I loved @mhitza idea, so I'm making it a little bigger...
The downside is the need to use .value
to reach the variable content.
Object.prototype.log = function(message) {
if (message) console.log(this.name, this.value, message);
else console.log(this.name, this.value);
}
function nar (name, value) {
var o = {name: name, value: value};
this[name] = o;
return o;
}
// var globalVar = 1;
nar('globalVar', 1);
globalVar.log();
// > globalVar 1
globalVar.value += 5;
globalVar.log('equal six');
// > globalVar 6 equal six
var someFunction = function () {
// var localVar = 2;
nar('localVar', 2);
localVar.log('someInfo');
// > localVar 2 someInfo
};
someFunction();
Surprised to see no super simple solution yet.
let varname = "banana"
console.log(`${JSON.stringify({varname}).split('"')[1]}`)
Prints varname
in the console
精彩评论