JavaScript 数组推送键值
好吧,我在这里有点错误,我已经浪费了一个小时,所以希望你们中的一个人可以帮助我。
var a = ['left','top'],
x = [];
for(i=0;i<a.length;i++) {
x.push({
a[i] : 0
});
}
如何将值推送到 var a 数组内的每个键?
您可以看到我失败的尝试,但希望这能让您深入了解我想要实现的目标。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您必须使用括号表示法:
结果将是:
也许您只想要一个具有两个属性的对象,而不是对象数组:
并且
这将导致
x = {left: 0, top: 0}.
You have to use bracket notation:
The result will be:
Maybe instead of an array of objects, you just want one object with two properties:
and
This will result in
x = {left: 0, top: 0}
.您可以使用:
数组.prototype.map()
Array.prototype.reduce()
箭头函数
逗号运算符
创建对象数组:
演示:
或者,如果您想从数组的值创建单个对象:
演示:
You may use:
Array.prototype.map()
Array.prototype.reduce()
Arrow functions
Comma operator
To create array of objects:
Demo:
Or if you wants to create a single object from values of arrays:
Demo: