在javascript中将变量名称转换为字符串 [英] get variable name into string in javascript

查看:110
本文介绍了在javascript中将变量名称转换为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

var abc = '123'

var def = '456'

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

need to write somefuntion() which convert variable name into string

喜欢

alert ("value of" +somefuntion(abc) +"is"+ abc +"and value of" +somefuntion(def)+" is"+def );

应该是这样的

alert ("value of abc is 123 and value of def is 456")



<我已经搜索并尝试了几个解决方案
和idk这个链接如何帮助因为我知道你会说它的重复但我尝试了它并没有工作

i have searched and tried few solution and idk how this link can help cuz i know you will say its duplicate but i tried it and it didnt work

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

推荐答案

使用下面的代码。

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 );

这基本上是做什么的,你将变量传递给 varToString 作为使用 {variable} 的对象。 varToString 然后返回一个数组,并将传递的变量作为 value

What this basicly does is, you pass the variable to varToString as an object using {variable}. varToString then returns an array with the passed variable as value.

[
  "abc"
]

我们使用 [0] 选择器(Object.keys(varObj)值 > [0] )。现在它返回

We grab this value using the [0] selector (Object.keys(varObj)[0]). Now it returns

abc

这篇关于在javascript中将变量名称转换为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆