Is it possible to define a dynamically named property using object literal in JavaScript?(是否可以在 JavaScript 中使用对象文字定义动态命名的属性?)
问题描述
考虑以下
var a = {foo: "bar"};
相当于
var a = {};
a.foo = "bar";
相当于
var a = {};
a['foo'] = "bar";
相当于
var a = {}
var b = "foo";
a[b] = "bar";
是否可以做类似的事情
var b = "foo";
var a = { [b]: "bar" };
这样的结果是
// => {foo: "bar"}
<小时>
可接受的解决方案是 JavaScript 或 CoffeeScript
Acceptable solutions are in JavaScript or CoffeeScript
推荐答案
ES6 支持计算属性.
ES6 supports computed properties.
// code from my original question now works in ES6 !
let b = "foo";
let a = { [b]: "bar" };
a.foo; //=> "bar"
[]
中可以使用任何表达式来定义属性名称
Any expression can be used within the []
to define the property name
let a = {
[(xs => xs.join(''))(['f','o','o'])]: 'bar'
};
a.foo; //=> "bar"
如果你需要在 ES5 世界中依赖这种行为,你可以依赖非常强大的 babel.js将您的 ES6 代码转换为 ES5 兼容的代码.
If you need to rely on this behavior in an ES5 world, you can lean on the very capable babel.js to transpile your ES6 code to ES5-compatible code.
这篇关于是否可以在 JavaScript 中使用对象文字定义动态命名的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:是否可以在 JavaScript 中使用对象文字定义动态命名的属性?


- 是否可以将标志传递给 Gulp 以使其以不同的方式 2022-01-01
- 从原点悬停时触发 translateY() 2022-01-01
- 我不能使用 json 使用 react 向我的 web api 发出 Post 请求 2022-01-01
- 为什么悬停在委托事件处理程序中不起作用? 2022-01-01
- 如何调试 CSS/Javascript 悬停问题 2022-01-01
- 在不使用循环的情况下查找数字数组中的一项 2022-01-01
- 如何显示带有换行符的文本标签? 2022-01-01
- 使用 iframe URL 的 jQuery UI 对话框 2022-01-01
- 为什么我的页面无法在 Github 上加载? 2022-01-01
- 如何向 ipc 渲染器发送添加回调 2022-01-01