gpt4 book ai didi

javascript - 通过每个循环创建具有多个属性的对象

转载 作者:行者123 更新时间:2023-12-02 17:38:20 25 4
gpt4 key购买 nike

自从我使用对象以来已经有一段时间了,所以我需要刷新我的内存。我需要帮助的是如何在每个循环中创建一个具有多个属性的对象。以下是我迄今为止尝试过的方法,但这显然是不正确的。

var imgs = {},
i = 0;

$('.img').each(function() {
i++;

imgs['img' + i]['src'] = src; // doesn't work

// imgs['img' + i] = src; <- works but I want several properties for every image.
});

所需输出:

imgs: {
img1: {
src: 'http://...',
otherProp: '...'
},
img2: {
src: 'http://...',
otherProp: '...'
},
and so on...
}

最佳答案

这应该是最简单的解决方案:

var imgs = {};

$('.img').each(function(index) {
imgs['img' + index] = {
src: src,
otherProp: ...
...
};
});

关于javascript - 通过每个循环创建具有多个属性的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22436337/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com