[英]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.) 编辑:从谷歌搜索“获取变量js的名称字符串”的结果来看,似乎没有简单的方法可以从引用中获取变量的名称字符串(您必须创建哈希表或其他使其不值得。)
So, the only possible solution would be to convert a string into a reference to the variable. 因此,唯一可能的解决方案是将字符串转换为对该变量的引用。 Is that possible in JS? 在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');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.