JavaScript 数组推送键值

发布于 2024-12-10 15:18:10 字数 251 浏览 3 评论 0 原文

好吧,我在这里有点错误,我已经浪费了一个小时,所以希望你们中的一个人可以帮助我。

var a = ['left','top'],
    x = [];

for(i=0;i<a.length;i++) {
    x.push({
        a[i] : 0
    });
}

如何将值推送到 var a 数组内的每个键?

您可以看到我失败的尝试,但希望这能让您深入了解我想要实现的目标。

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
    });
}

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

如果没结果 2024-12-17 15:18:10

您必须使用括号表示法:

var obj = {};
obj[a[i]] = 0;
x.push(obj);

结果将是:

x = [{left: 0}, {top: 0}];

也许您只想要一个具有两个属性的对象,而不是对象数组:

var x = {};

并且

x[a[i]] = 0;

这将导致 x = {left: 0, top: 0}.

You have to use bracket notation:

var obj = {};
obj[a[i]] = 0;
x.push(obj);

The result will be:

x = [{left: 0}, {top: 0}];

Maybe instead of an array of objects, you just want one object with two properties:

var x = {};

and

x[a[i]] = 0;

This will result in x = {left: 0, top: 0}.

浪漫人生路 2024-12-17 15:18:10

您可以使用:


创建对象数组:

var source = ['left', 'top'];
const result = source.map(arrValue => ({[arrValue]: 0}));

演示:

var source = ['left', 'top'];

const result = source.map(value => ({[value]: 0}));

console.log(result);


或者,如果您想从数组的值创建单个对象:

var source = ['left', 'top'];
const result = source.reduce((obj, arrValue) => (obj[arrValue] = 0, obj), {});

演示:

var source = ['left', 'top'];

const result = source.reduce((obj, arrValue) => (obj[arrValue] = 0, obj), {});

console.log(result);

You may use:


To create array of objects:

var source = ['left', 'top'];
const result = source.map(arrValue => ({[arrValue]: 0}));

Demo:

var source = ['left', 'top'];

const result = source.map(value => ({[value]: 0}));

console.log(result);


Or if you wants to create a single object from values of arrays:

var source = ['left', 'top'];
const result = source.reduce((obj, arrValue) => (obj[arrValue] = 0, obj), {});

Demo:

var source = ['left', 'top'];

const result = source.reduce((obj, arrValue) => (obj[arrValue] = 0, obj), {});

console.log(result);

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文