0

Hello, Why this code is not working ? I spent a whole day looking for the issue.Hope someone can help me.

In this code you can see that if the user clicked the [click] button more than one time,The message "already added" needs to be displayed in the console,But this code is not working.I don't know why Array.includes() is not working properly in this array of objects,please check the code. https://code.sololearn.com/WzsBmd19E6ux/?ref=app

3rd May 2022, 1:41 AM
roshan roy
6 ответов
+ 1
const btn= document.getElementById("btn"); let arr = []; class Obj { constructor(name, age) { this.name = name; this.age= age; } } btn.addEventListener("click",() => { let newObj = new Obj("roshan",18); if(arr.includes(newObj.name) == false){ arr.push(newObj.name); }else{ console.log("Already added"); } console.log(arr); // To display })
3rd May 2022, 3:19 AM
SoloProg
SoloProg - avatar
+ 1
I mean how is the program supposed to know what make your object unique ? Since you could for exaple have Obj (“roshan”,20) Obj (“roshan”,5) The way you have it, its defaulting to comparing the address.
3rd May 2022, 3:48 AM
Raul Ramirez
Raul Ramirez - avatar
+ 1
https://code.sololearn.com/WW9z0Ikg1Ck3/?ref=app You are comparing new object with older ones js Check that
3rd May 2022, 5:26 AM
Shahghasi Adil
Shahghasi Adil - avatar
0
One thing is You never set the object attributes
3rd May 2022, 3:13 AM
Raul Ramirez
Raul Ramirez - avatar
0
Bro, what if I do not use newObj.name? I mean I need to add the whole object and if that already exists then don't.
3rd May 2022, 3:37 AM
roshan roy
3rd May 2022, 9:55 PM
Bob_Li
Bob_Li - avatar