简体   繁体   中英

JS. Object in array?

I'm learning js, find this code:

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 ?

{} 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.

...how i can work with this data and display this ?

To display the id , for instance:

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

What that does:

  • arr[0] - retrieve the first entry in the array. In our case, it's an object.

  • .id - Get the value of the id property from that object.

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

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

You can then access properties of the object, for example arr[0].id .

For more about objects, take a look at Objects on MDN .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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