如何在Javascript中创建对象中的对象

igetnqfo  于 2022-12-21  发布在  Java
关注(0)|答案(6)|浏览(156)

我正在尝试创建一个对象-其中的每个参数都是另一个对象:

var divTextPerScreenWidthMap = new Object(
       {'360','click'},
       {'480','click it'},
       {'768','click it right'},
       {'1024','you know you want to click it'},
       {'1280','click this button which is very long will help you'}
    );

这是不工作,因为我得到了一个错误。我需要如何写它,使其工作?我应该改变外部对象到一个数组,以及如何?

6jjcrrmo

6jjcrrmo1#

你有语法错误。
首先,对象文字遵循以下语法:

var literal = {
    "Name": "value",
    "Array": [],
    "NestedObject": {}
};

名称值分隔符是冒号,而不是逗号。

    • 编辑**

上述代码可以重写如下

// declaration via array initializer
var myArray = [
   // name : value syntax
   {'360': 'click'},
   // values separated by comma
   {'480': 'click it'},
   {'768': 'click it right'},
   {'1024': 'you know you want to click it'},
   {'1280': 'click this button which is very long will help you'}
]

然而,此时您无法通过以下名称访问对象:

var firstObject = myArray[0];
// will throw an error
firstObject.360 = "not click";

您只能按以下方式使用它

firstObject["360"] = "not click";

因此,我建议您根据变量命名规则来命名属性。

ldioqlga

ldioqlga2#

在javascript中对象是一个简单的Map,最好使用literal {}代替new Object();

var myObj = {      
     prop : {},
     prop2 : {} 
   }
nhn9ugyo

nhn9ugyo3#

不要通过构造函数创建Object,使用字面语法{}
同样,对象有键和属性。你的对象似乎只有值。你的意思是使用Array s吗?

n9vozmp4

n9vozmp44#

你完全忘了给你的值给予键,如果你不想用键,那就用数组:

var divFoo = [
  [360, "click"],
  [480, "click it"] // et cetera
];

这将给予你一个数组的数组。例如,divFoo[0][0] == 360
如果需要密钥,请使用对象:

var divFoo = {
  "360": "click",
  "480": "click" // et cetera
}

这将为您提供简单的对象。divFoo[360] == "click"
或者,您可以使用对象数组来获得更多描述性:

var divFoo = [
  {time: 360, text: "click"},
  {time: 480, text: "click it"} // et cetera
];

在本例中为divFoo[1].text == "click it"
还有几点提示:

  • 不要使用new Objectnew Array,它们是多余的。
  • 如果整数被用作值,就不需要用引号引起来。
tjjdgumg

tjjdgumg5#

将对象集合表示为数组是有意义的:

var divTextPerScreenWidthMap = [
           {360:'click'},
           {480:'click it'},
           {768:'click it right'},
           {1024:'you know you want to click it'},
           {1280:'click this button which is very long will help you'}
        ];

//You could iterate over your array of objects with a for loop:
        
      var i, value;
      for (i=0; i < divTextPerScreenWidthMap.length; i++) {
        value = divTextPerScreenWidthMap[i];
        console.log(value);
      };


//Alternatively, you could represent your data structure as one object:

    var divTextPerScreenWidthMap = {
           360:'click',
           480:'click it',
           768:'click it right',
           1024:'you know you want to click it',
           1280:'click this button which is very long will help you'
        };
    
//So now if you have a screen width, you can quickly get back the corresponding message:

    var screenWdith = 360;
    alert(divTextPerScreenWidthMap[screenWidth]);
ovfsdjhp

ovfsdjhp6#

您还可以创建如下所示的嵌套对象:

let obj1 = {};
obj1['title'] = 'Vehicles';

let obj2 = {};
obj2['name'] = 'Honda City';

obj1['cars'] = obj2;

console.log(obj1);

相关问题