本文介绍了JavaScript 数组推送键值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
好的,我在这里有点不对劲,我已经浪费了一个小时,所以希望你们中的一个能帮助我.
Ok, I'm going a little wrong here and I've already wasted an hour with this so hopefully one of you guys can help me.
var a = ['left','top'],
x = [];
for(i=0;i<a.length;i++) {
x.push({
a[i] : 0
});
}
如何将值推送到 var a
数组中的每个键?
How do I go about pushing a value to each of the keys inside the var a
array?
你可以看到我失败的尝试,但希望这能让你深入了解我正在努力实现的目标.
You can see my failed attempted but hopefully that will give you an insight into what I'm trying to achieve.
推荐答案
必须使用括号表示法:
var obj = {};
obj[a[i]] = 0;
x.push(obj);
结果将是:
x = [{left: 0}, {top: 0}];
也许您只需要一个具有两个属性的对象,而不是一组对象:
Maybe instead of an array of objects, you just want one object with two properties:
var x = {};
和
x[a[i]] = 0;
这将导致 x = {left: 0, top: 0}
.
这篇关于JavaScript 数组推送键值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!