如何在JavaScript中声明嵌套对象? [英] How to declare nested objects in JavaScript?
问题描述
我正在尝试创建一个包含对象的对象,因此将其视为字典:
I'm trying to create an object that contains an object, so think of it as a dictionary:
var dictionaries = {};
dictionaries.english_to_french =
{
{english:"hello",french:"bonjour"},
{english:"i want",french:"je veux"},
{english:"bla",french:"le bla"}
};
但是它给出了错误未捕获的SyntaxError:意外的令牌{
我做错了什么?
but it gives the error Uncaught SyntaxError: Unexpected token {
what am I doing wrong?
谢谢!
对不起,我没有澄清我想做什么。
编辑上面的代码。
I'm sorry that I did not clarify what I want to do. Edited the code above.
推荐答案
你试图给你的对象一个属性,那个属性将是单个对象:
You're trying to give your object a property, and that property will be a single object:
dictionaries.english_to_french =
{english:"hello",french:"bonjour"}
;
您不需要额外的 {}
。你可以一次声明整个事情:
You don't need the extra { }
. You could declare the whole thing at once:
var dictionaries = {
english_to_french: {
english: "hello", french: "bonjour"
}
};
我建议你的词典更好的格式是:
I would suggest that a better format for your dictionaries might be:
var dictionaries = {
english_to_french: {
"hello": "bonjour",
"chicken": "poulet", // ? something like that
"Englishman": "rosbif"
}
};
这样你就可以直接查找单词而无需搜索。然后你可以从那里创建反向字典:
That way you can look up words directly without having to search. You could then create the reverse dictionary from that:
dictionaries.french_to_english = function(dict) {
var rv = {};
for (var eword in dict)
rv[dict[eword]] = eword;
return rv;
}(dictionaries.english_to_french);
这篇关于如何在JavaScript中声明嵌套对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!