简体   繁体   中英

How do I access an object's properties in an array?

I have a collection called ChatRooms that has an array called messages in it. Inside messages, at each index is an object containing the properties name and message. How do i access the last object's name property in the javascript?

something like this:

 var messagerName = ChatRooms.find(messages.name); 
var messages = [...] // this array assumes you have many objects inside it.

To access the last object:

var index = messages.length - 1;

The .length returns the length of an array (number of objects inside the array). Remember, the first object is indexed at the value 0, so this is why we subtract 1.

var lastObject = messages[index];

Use dot notation to access the properties inside the object.

Eg

var name = lastObject.name;

如果您说最后一个对象是指最后一条消息,请尝试以下操作:

var messagerName = ChatRooms.find(messages[messages.length - 1].name); 

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