0

私はこのコードを見つけました...

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
  • 単なる数字ではなく、名前付きのキーです。設定が増えるとさらに良いです。
4

3 に答える 3

1

配列ではなくオブジェクトが必要なようです:

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
于 2013-10-30T08:59:55.480 に答える