如何在 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"}
};
但它给出了错误 Uncaught SyntaxError: Unexpected token {
我做错了什么?
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屋!