变量名作为 Javascript 中的字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4602141/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Variable name as a string in Javascript
提问by fish potato
Is there a way to get a variable name as a string in Javascript? (like NSStringFromSelector
in Cocoa)
有没有办法在Javascript中将变量名作为字符串获取?(就像NSStringFromSelector
在可可中)
I would like to do like this:
我想这样做:
var myFirstName = 'John';
alert(variablesName(myFirstName) + ":" + myFirstName);
--> myFirstName:John
UPDATE
更新
I'm trying to connect a browser and another program using JavaScript. I would like to send instance names from a browser to another program for callback method:
我正在尝试使用 JavaScript 连接浏览器和另一个程序。我想将实例名称从浏览器发送到另一个程序以进行回调方法:
FooClass = function(){};
FooClass.someMethod = function(json) {
// Do something
}
instanceA = new FooClass();
instanceB = new FooClass();
doSomethingInAnotherProcess(instanceB); // result will be substituted by using instanceB.someMethod();
...
From another program:
从另一个程序:
evaluateJavascriptInBrowser("(instanceName).someMethod("resultA");");
In PHP: How to get a variable name as a string in PHP?
在 PHP 中:如何在 PHP 中以字符串形式获取变量名?
采纳答案by karim79
Typically, you would use a hash table for a situation where you want to map a name to some value, and be able to retrieve both.
通常,在希望将名称映射到某个值并且能够检索两者的情况下,您会使用哈希表。
var obj = { myFirstName: 'John' };
obj.foo = 'Another name';
for(key in obj)
console.log(key + ': ' + obj[key]);
回答by Donuts
Like Seth's answer, but uses Object.keys()
instead:
像赛斯的回答一样,但使用Object.keys()
:
const varToString = varObj => Object.keys(varObj)[0]
const someVar = 42
const displayName = varToString({ someVar })
console.log(displayName)
回答by Fellow Stranger
You can use the following solution to solve your problem:
您可以使用以下解决方案来解决您的问题:
const myFirstName = 'John'
Object.keys({myFirstName})[0]
// returns "myFirstName"
回答by SethWhite
In ES6, you could write something like:
在 ES6 中,你可以这样写:
let myVar = 'something';
let nameObject = {myVar};
let getVarNameFromObject = (nameObject) => {
for(let varName in nameObject) {
return varName;
}
}
let varName = getVarNameFromObject(nameObject);
Not really the best looking thing, but it gets the job done.
不是最好看的东西,但它完成了工作。
This leverages ES6's object destructuring.
这利用了 ES6 的对象解构。
More info here: https://hacks.mozilla.org/2015/05/es6-in-depth-destructuring/
更多信息:https: //hacks.mozilla.org/2015/05/es6-in-depth-destructuring/
回答by cloverink
var x = 2;
for(o in window){
if(window[o] === x){
alert(o);
}
}
However, I think you should do like "karim79"
但是,我认为你应该像“karim79”一样
回答by BrunoLM
This works for basic expressions
这适用于基本表达式
const nameof = exp => exp.toString().match(/[.](\w+)/)[1];
Example
例子
nameof(() => options.displaySize);
Snippet:
片段:
var nameof = function (exp) { return exp.toString().match(/[.](\w+)/)[1]; };
var myFirstName = 'Chuck';
var varname = nameof(function () { return window.myFirstName; });
console.log(varname);
回答by Juangui Jordán
Probably pop would be better than indexing with [0], for safety (variable might be null).
为了安全起见(变量可能为空),pop 可能比使用 [0] 索引更好。
const myFirstName = 'John'
const variableName = Object.keys({myFirstName}).pop();
console.log(`Variable ${variableName} with value '${variable}'`);
// returns "Variable myFirstName with value 'John'"
回答by Cadiboo
var somefancyvariable = "fancy";
Object.keys({somefancyvariable})[0];
This isn't able to be made into a function as it returns the name of the function's variable.
这不能成为一个函数,因为它返回函数变量的名称。
// THIS DOESN'T WORK
function getVarName(v) {
return Object.keys({v})[0];
}
// Returns "v"
// THIS DOESN'T WORK
function getVarName(v) {
return Object.keys({v})[0];
}
// Returns "v"
Edit: Thanks to @Madeofor pointing out how to make this into a function.
编辑:感谢@Madeo为指出如何使之成为一个功能此。
function debugVar(varObj) {
var varName = Object.keys(varObj)[0];
console.log("Var \"" + varName + "\" has a value of \"" + varObj[varName] + "\"");
}
You will need call the function with a single element array containing the variable. debugVar({somefancyvariable});
Edit: Object.keys
can be referenced as just keys
in every browser I tested it in but according to the comments it doesn't work everywhere.
您将需要使用包含变量的单元素数组调用该函数。debugVar({somefancyvariable});
编辑:Object.keys
可以keys
在我测试过的每个浏览器中引用,但根据评论,它并不适用于所有地方。
回答by Benny Neugebauer
Since ECMAScript 5.1you can use Object.keysto get the names of all properties from an object.
从ECMAScript 5.1 开始,您可以使用Object.keys从对象中获取所有属性的名称。
Here is an example:
下面是一个例子:
// Get John's properties (firstName, lastName)
var john = {firstName: 'John', lastName: 'Doe'};
var properties = Object.keys(john);
// Show John's properties
var message = 'John's properties are: ' + properties.join(', ');
document.write(message);
回答by Matt Smith
When having a function write a function that changes different global variables values it is not always myfirstname it is whatever happens to be passing through. Try this worked for me.
当让一个函数编写一个改变不同全局变量值的函数时,它并不总是 myfirstname,它是碰巧通过的任何东西。试试这对我有用。
Run in jsfiddle
在jsfiddle 中运行
var Hyman = 'jill';
function window_getVarName(what)
{
for (var name in window)
{
if (window[name]==what)
return(name);
}
return("");
}
document.write(window_getVarName(Hyman));
Will write to the window 'Hyman'.
将写入窗口“Hyman”。