使用索引向特定对象属性添加数据

Add data to specific object property with index

本文关键字:对象 属性 添加 数据 索引      更新时间:2023-09-26

我有一个像这样的对象:

imgs: {
    img1: {
        on: 0,
        scr: null
    },
    img2: {
        on: 0,
        scr: null
    },
    and so on...
}

我想要的是使用被点击图像的索引来到达对象中的特定图像属性。

js:

MoveUpImg: function(index) {
    Capsule.imgs['img' + index].on = 1;
    // rest of the code
},

这段代码不起作用:

Uncaught TypeError: Cannot set property 'on' of undefined

通过改变一个特定的对象属性,比如img2,它可以工作:

Capsule.imgs.img2.on = 1;

…这意味着问题出在这一行:

Capsule.imgs['img' + index].on = 1;

(当然我已经检查了索引是否给出了正确的数字等等)

您正在将img传递给功能,但试图访问imgs对象

应该

MoveUpImg: function(imgs, index) {

代替

MoveUpImg: function(img, index) {