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 中使用对象文字定义动态命名的属性?


基础教程推荐
- Bokeh Div文本对齐 2022-01-01
- 如何添加到目前为止的天数? 2022-01-01
- 即使用户允许,Gmail 也会隐藏外部电子邮件图片 2022-01-01
- fetch 是否支持原生多文件上传? 2022-01-01
- Fabric JS绘制具有活动形状的多边形 2022-01-01
- Bootstrap 模态出现在背景下 2022-01-01
- 检查 HTML5 拖放文件类型 2022-01-01
- 原生拖动事件后如何获取 mouseup 事件? 2022-01-01
- npm start 错误与 create-react-app 2022-01-01
- 在 contenteditable 中精确拖放 2022-01-01