使用连字符引用对象的属性名称

Pet*_*jda 2 javascript

我定义了一个对象,其属性名称中带有连字符。

var data = {
  "foo-bar": "value",
  "this-that": "another value"
}
Run Code Online (Sandbox Code Playgroud)

现在我需要在JS中引用这个属性,但这两种方式都会导致语法错误。

console.log( data.foo-bar )
Run Code Online (Sandbox Code Playgroud)

console.log( data."foo-bar" )
Run Code Online (Sandbox Code Playgroud)

所以我的问题是。如何在 JS 中访问名称中包含连字符的属性?


免责声明:服务器端功能需要对属性进行连字符命名,我真的不想重写别人的整个脚本来接受这样的输入参数。是的,我知道目前的方法并不是最干净的方法。

Jen*_*ohn 5

你可以改用data["foo-bar"]