JavaScript函数,该函数返回布尔类型的变量名,而不是模板文本中的值本身

JavaScript函数,该函数返回布尔类型的变量名,而不是模板文本中的值本身,javascript,reactjs,ecmascript-6,Javascript,Reactjs,Ecmascript 6,“javascript”中是否有一个函数,可以将变量(而不是值)设置为字符串,比如parseVariableName之类的内容 例如,在我的场景中,我希望使用布尔变量创建**动态类名,而不创建对象,使其成为数组和循环。我想返回变量名,而不是变量的值。有了它,我可以在模板文本中使用它 const { isPivotable = true, isTable, isGrid } = props const cn = `myClass--sample ${isPivotable || isTable

“javascript”中是否有一个函数,可以将变量(而不是值)设置为字符串,比如parseVariableName之类的内容

例如,在我的场景中,我希望使用布尔变量创建**动态类名,而不创建对象,使其成为数组和循环。我想返回变量名,而不是变量的值。有了它,我可以在模板文本中使用它

const { isPivotable = true, isTable, isGrid } = props

const cn =  `myClass--sample ${isPivotable || isTable || isGrid}`

//or

const isPivotable = true, 
const isTable = false
const isGrid = false

const cn =  `myClass--sample ${isPivotable || isTable || isGrid}`

//value true is converted as STRING
actual result: *myClass--sample true* 

//the variable isPivotTable "name" converted as string
expected result: *myClass--sample isPivotable*
预期结果的示例,但使用了我想要避免的对象和数组

const parseVariableName = (obj) => Object.entries(obj).reduce((acc, [key, val])=> !acc && val ? key : acc, '')

isPivotable = false
isGrid = false
isDraggableTable = true

const answer = `class-sample--${parseVariableName({ isPivotable, isGrid, isDraggableTable})}`
console.log(answer)
为什么我问这个问题,是因为我想在我声明的变量的基础上创建一个变量名,我不想因为它而使我的代码变长


我知道问这个问题很愚蠢,但我只想和大家分享我的想法。

我不太清楚你们到底想在这里实现什么。但是为了得到预期的结果,我可以想到以下几点:您可以将所有变量放在一个对象中,而不是将其放在默认的
窗口
对象中。这里我使用的是
prop
。这样,您就可以将整个对象传递到一个函数中,在该函数中检查第一个
true
值出现的位置(其行为类似于示例中的OR链)。然后返回真值的
,然后可以将其用作类。下面是一个工作示例

let prop={
isPivotable:是的,
isTable:错误,
isGrid:false
}
函数doCompare(prop){
让发现=“”;
(Object.keys(prop)).some(x=>{
如果(第[x]号提案){
发现=x;
返回true;
}
})
发现退货;
}
const cn=`myClass--sample${doCompare(prop)}`

console.log(cn)不是真的。我所做的:
constcns=[“myClass--sample”]
then
if(isPivotable | isTable | isGrid)cns.push(“可旋转”)。渲染时,我使用
cns.join(“”
)。您还可以使用
element.classList.add(“可透视”)我对我的问题也有一个答案,但我正在寻找一个“javascript方法”,这是我的答案:
const variableNameToString=(obj)=>Object.entries(obj).reduce((acc,[key,val])=>!acc&&val?key:acc,,)isPivotable=false isGrid=false isDraggableTable=true const ans=
类示例--${variableNameToString({isPivotable,isGrid,isDraggableTable}``在“javascript”中是否有一个函数,我可以将变量(而不是值)作为字符串,比如parseVariableName之类的东西?”不,没有,而且这似乎是一条危险的路径。如果代码由重命名变量的迷你程序处理,结果会发生变化。是的,我也得到了我的,但使用了reduce。请参阅上面的注释部分。我真的怀疑是否有更多的Javascript方法可以做到这一点。我们声明的变量只不过是
windows
object。在大型windows对象上运行reduce非常困难。我使用了reactjs。