如何在 JavaScript 中声明嵌套对象?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17778297/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 09:36:04  来源:igfitidea点击:

How to declare nested objects in JavaScript?

javascriptobjectnestedmultidimensional-array

提问by jeff

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"}
};

but it gives the error Uncaught SyntaxError: Unexpected token {what am I doing wrong?

但它给出了错误Uncaught SyntaxError: Unexpected token {我做错了什么?

Thanks !

谢谢 !

Edit

编辑

I'm sorry that I did not clarify what I want to do. Edited the code above.

很抱歉我没有说明我想做什么。编辑了上面的代码。

采纳答案by Pointy

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);

回答by John Woodruff

In order to nest two or more objects, the objects need to have an attribute assigned to them. For example,

为了嵌套两个或多个对象,这些对象需要具有分配给它们的属性。例如,

{
    "hello":{
        "english":"hello",
        "french":"bonjour",
        "portuguese":"ola"
    },
    "good day":{...},
    "how are you":{...}
}

"hello" at the beginning of the object would be the attribute. Then the object is its value. So that way you can access the object by accessing its attribute. Just putting an object in an object does not work. That's why you're getting your error.

对象开头的“hello”将是属性。那么对象就是它的值。这样您就可以通过访问其属性来访问该对象。仅仅将一个对象放在一个对象中是行不通的。这就是为什么你会得到你的错误。