在JavaScript中将变量名称转换为字符串

Aht*_*haq 6 javascript string variables

var abc = '123'

var def = '456'
Run Code Online (Sandbox Code Playgroud)

需要写somefuntion()将变量名转换为字符串

喜欢

alert ("value of" +somefuntion(abc) +"is"+ abc +"and value of" +somefuntion(def)+" is"+def );
Run Code Online (Sandbox Code Playgroud)

应该是这样的

alert ("value of abc is 123 and value of def is 456")
Run Code Online (Sandbox Code Playgroud)

我已经搜索并尝试了一些解决方案和idk,该链接如何帮助cuz我知道您会说它的重复项,但是我尝试了它但没有成功

如何在JS中将变量名转换为字符串?

Red*_*Red 9

使用下面的代码。

const abc = '123';
const def = '456';

const varToString = varObj => Object.keys(varObj)[0]

alert ("value of " +varToString({def}) +" is "+ def +" and value of " +varToString({abc})+" is "+abc );
Run Code Online (Sandbox Code Playgroud)

这基本上是做的,您可以使用将变量varToString作为对象传递给{variable}varToString然后返回array带有传递的变量作为value的

[
  "abc"
]
Run Code Online (Sandbox Code Playgroud)

我们使用选择器(Object.keys(varObj)[0])来获取此。现在它返回[0]

abc
Run Code Online (Sandbox Code Playgroud)