Javascript-方法名称的变量?

Javascript-方法名称的变量?,javascript,variables,indirect-objects,Javascript,Variables,Indirect Objects,如何间接引用javascript对象 假设: <div id="foo" data-munchy="bar" data-crunchy="baz">FooBar</div> <script> document.getElementById("foo").onclick = function() { tempVariable = 'munchy'; console.log(this.dataset.tempVariable); } </s

如何间接引用javascript对象

假设:

<div id="foo" data-munchy="bar" data-crunchy="baz">FooBar</div>

<script>
document.getElementById("foo").onclick = function() {
    tempVariable = 'munchy';
    console.log(this.dataset.tempVariable);
}
</script>
FooBar
document.getElementById(“foo”).onclick=function(){
tempVariable='munchy';
console.log(this.dataset.tempVariable);
}
如何访问
此.dataset.{someVariable}
?在本例中,
this.dataset.tempVariable


是否只能使用
eval
window

使用方括号表示法:

this.dataset[tempVariable];

使用方括号表示法:

this.dataset[tempVariable];

您想要
这个.dataset[tempVariable]
这个.dataset[tempVariable]对于您的示例,与
这个.dataset.muncy
相同。可能是@lealcelderio的重复。我不知道为什么我这么难找到它。可能这个问题的措辞与不熟悉这个概念的人不相关。你想要
这个.dataset[tempVariable]
这个。dataset[tempVariable]
对于你的例子来说,与
这个.dataset.muncy
相同。可能是@lealcelderio的重复。我不知道为什么我这么难找到它。可能这个问题的措辞与不熟悉这个概念的人不相关。@VictorToddard-不,这将查找字符串
tempVariable
-按OP最初的字面意思:
this.dataset.tempVariable
这很好。我不知道它们可以同时访问属性和数组。谢谢,@Kevin@VictorStoddard-不,这将查找字符串
tempVariable
-实际上是OP最初拥有的:
this.dataset.tempVariable
,这太棒了。我不知道它们可以同时访问属性和数组。谢谢,凯文。