在多个对象属性字段上存储单个元素的属性

Storing attributes for a single element over multiple object property fields

本文关键字:属性 存储 单个 元素 字段 对象      更新时间:2023-09-26

将应用于单个元素的属性分散到多个对象属性中的多个数组中是否被认为是不好的做法?

var properties={};
properties.name=['fish','car','plane','boat', UP TO 1000];
properties.color=['blue','green','yellow','magenta','etc'];
properties.link=['link1','link2','link3','etc'];
properties.date=[,,,,,];   
properties.XY=[,,,,,];   
properties.subject=[,,,,,];   
properties.createdBy=[,,,,,];   
Element.name=properties.name[1];
Element.color=properties.color[1];
Element.link=properties.link[1];
Element.onclick=properties.date[1];

我最初使用嵌入函数或闭包的数组,但得到了很多负面反馈。也没有兴趣使用库到目前为止。

不要将每个属性放在单独的数组中,而是创建一个对象数组:

var properties = [
    { name: 'fish',
      color: 'blue',
      link: 'link1'
    },
    { name: 'car',
      color: 'green',
      link: 'link2'
    }
    ...
];

然后你可以直接访问Element = properties[i],它会在一个地方包含你想要的所有属性。

为了避免重复所有的属性名,你可以写这样一个函数:

function makeProp (name, color, link) {
    return { name: name, color: color, link: link };
}

那么你的数组看起来像:

var properties = [
    makeProp('fish', 'blue', 'link1'),
    makeProp('car', 'green', 'link2'),
    ...
];