简体   繁体   English

“ console.log(“ var:“ + var)”的简写?

[英]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.

相关问题 falsey var在console.log中显示未定义 - falsey var showing undefined in console.log 这是console.log的简写吗? - Is this a shorthand for console.log? 如果console.log(…arguments)正常,为什么var a =…arguments失败? - Why does var a = …arguments fail, if console.log(…arguments) is OK? JavaScript var === 2 &amp;&amp; console.log(&#39;true&#39;)。 这是如何运作的? - Javascript var === 2 && console.log('true'). How does this work? 离子模板中的 var 未定义,但 console.log 显示它 - var in ionic template undefined, but console.log displays it 在 JavaScript var x=2,var y=“2”; console.log(xy),为什么 o/p 为 0? - In JavaScript var x=2, var y=“2”; console.log(x-y), why is o/p 0? 以下代码行的 output 是什么? 变量 x = null; 变量 z = “sp”; 如果 (x==true){ z+=1; } 控制台.log(z); * - What is the output for the following lines of code? var x = null; var z = “sp”; if (x==true){ z+=1; } console.log(z); * 如何将“console.log(name[0])”插入变量“var letter”? - how can i insert "console.log(name[0])" into the variable "var letter"? 我想 console.log 数组的 var_dump 值。 我怎么做? - I want to console.log value of var_dump of array. How do I do that? 为什么在“ $ http” AngularJS中执行“ console.log()”时无法从var_dump获得结果 - Why do not I get results from var_dump, while doing 'console.log()' in '$http' AngularJS
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM