简体   繁体   中英

Finding an custom element in an array Javascript

I created a class in JavaScript like

function chat(data){
this.id = data.id;
this.name = data.name;
this.message = data.message
this.date = data.date;
}

Now i declare an array like this.

     var message = [];

and push my chat object in message array;

var chat = new chat(data);
message.push(chat);

What is the best possible way to find the elements in message array by id. Or any thing else which make it easier also i need to short the array using date also.

Loop. Since chat is an object you cannot use Array.indexOf.

If you instead do

var Message = {};
Message[data.id]=new chat(data);

If chat() is as simple as you show, then just do

Message[data.id]=data;

Then you can access either directly by id

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