简体   繁体   English

JS。 数组中的对象?

[英]JS. Object in array?

I'm learning js, find this code: 我正在学习js,请找到以下代码:

var arr = [ 
 {id: 111, now: '12.02.2014'}
]; 

What is this? 这是什么? I know that var arr = [ ... ] - array, but what is {} in array and how i can work with this data and display this ? 我知道var arr = [...]-数组,但是数组中的{}是什么,我如何处理这些数据并显示呢?

{} is the syntax for creating an object. {}是用于创建对象的语法。 It's called an object initializer , but it's frequently called an "object literal". 它被称为对象初始化器 ,但通常被称为“对象文字”。

So what you're doing there is creating an object which has id and now properties, and putting that object into an array as its only entry. 因此,您要做的就是创建一个具有idnow属性的对象,并将该对象作为唯一条目放入数组。

...how i can work with this data and display this ? ...我如何处理这些数据并显示它?

To display the id , for instance: 要显示id ,例如:

console.log(arr[0].id);

What that does: 那是什么:

  • arr[0] - retrieve the first entry in the array. arr[0] -检索数组中的第一个条目。 In our case, it's an object. 在我们的例子中,它是一个对象。

  • .id - Get the value of the id property from that object. .id从该对象获取id属性的值。

We could also write it like this: 我们也可以这样写:

var obj = arr[0];
console.log(obj.id);

Alternately, if we didn't know in advance what property we wanted but we were given a string containing the name of the property, we could use [] with the object as well: 或者,如果我们事先不知道想要什么属性,但是给了我们一个包含属性名称的字符串,那么我们也可以将[]与对象一起使用:

var nameOfProperty = "id";
var obj = arr[0];
console.log(obj[nameOfProperty]);

JavaScript has both the dotted syntax ( obj.id ), and the bracketed syntax ( obj["id"] ) for accessing object properties, where with the latter you can use any string (including one from a variable). JavaScript具有点语法( obj.id )和带括号的语法( obj["id"] ),用于访问对象属性,在后者中,您可以使用任何字符串(包括变量中的一个)。

Yes, that is an object inside an array. 是的,那是数组内的对象。 In truth, all values, from numbers to functions to arrays, are actually objects. 实际上,从数字到函数再到数组的所有值实际上都是对象。

You can access this object in the same way as you would any item of an array. 您可以使用与数组中任何项目相同的方式访问此对象。 ( arr[0] ) arr[0]

You can then access properties of the object, for example arr[0].id . 然后,您可以访问对象的属性,例如arr[0].id

For more about objects, take a look at Objects on MDN . 有关对象的更多信息,请查看MDN上的对象

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM