这个问题 Javascript: Reference a variable name from the variable itself 知道变量名称的解决方案是搜索存储该名称的属性。但是,这给出了变量的名称,但没有给出“原始”变量的名称。
难以解释,使用代码更好:
const IndividualValue = (hello) => console.log(Object.keys({hello})[0]);
let theNameOfTheVariable = 'very important info';
IndividualValue(theNameOfTheVariable);
我想要
theNameOfTheVariable
但是我得到了
hello
有可能吗?或者我需要在第二个变量中发送名称,例如
const IndividualValue = (hello, name) => console.log(name);
let theNameOfTheVariable = 'very important info';
IndividualValue(theNameOfTheVariable, 'theNameOfTheVariable');
编辑:从重复标记开始,解决方案应该是:
const IndividualValue = (hello) => console.log(Object.keys(hello)[0]);
let theNameOfTheVariable = 'very important info';
IndividualValue({theNameOfTheVariable});
但是,它对我不起作用。问题在于变量是一个对象,因此以下代码不起作用(在我手中,在JSX代码中):
const IndividualValue = (hello) => console.log(Object.keys(hello)[0]);
let item = {};
item.theNameOfTheVariable = 'very important info';
IndividualValue({item.theNameOfTheVariable}); // syntax error with the dot