我找到了这段代码......
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
。答案 0 :(得分: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
答案 1 :(得分:0)
在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);
答案 2 :(得分:0)
你试过这个:table['font'] = newFont;
?