具有命名键的数组对象

array object with named key

本文关键字:数组 对象      更新时间:2023-09-26

我找到了这段代码...

var newEntry, table = [];
newEntry = {
    id: '321',
    price: '1000',
};
table.push(newEntry);
alert(table[0].id);

它按预期工作。但是我需要添加多个条目,就像这样...

var newFont, newColor, table = [];
newFont = {
    family: 'arial',
    size: '12',
};
newColor = {
    hex: 'red',
};
table.push(newFont);
table.push(newColor);
alert(table[0].font);

问题

  • 我不想写table[0].family.
  • 相反,我想写table['font'].family.
  • 它是一个命名键,而不仅仅是一个数字。如果设置增加会更好。

听起来你想要一个对象,而不是一个数组:

var settings = {
    font: {
        family: 'arial',
        size: '12'
    },
    color: {
        hex: 'red'
    }
};
alert(settings.font.family);    // one way to get it
alert(settings['font'].family); // another way to get it

在 JavaScript 中,数组不能有命名键,但您可以将table更改为对象并使用命名键。

var newFont, newColor, table = {};
newFont = {
    family: 'arial',
    size: '12',
};
newColor = {
    hex: 'red',
};
table.font = newFont;
table.color = newColor;
console.log(table['font'].family);
console.log(table.font.family);

你试过这个吗:table['font'] = newFont;