+ 1
I don't know why includes() returns false
https://code.sololearn.com/Wo9KM4yqeBE3/?ref=app Edit: An alternative title can be "can i use includes() on an array of objects?"
3 Antworten
0
you cannot compare object this way:
"Technically speaking, includes() uses the sameValueZero algorithm to determine whether the given element is found."
source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes
see also: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness#same-value-zero_equality
it means that includes internally do a kind of === equality comparison (except that NaN === NaN)
so, you need to test if all properties of object source === or == all properties of target object, and reciprocally... including it's constructor and __proto__ are also equals if needed ^^
comparison of object "by value" isn't obvious, as can be implemented from many ways, depending on your needs (stritcly equals if same object reference -- what includes roughly do -- less or more strictly equals by comparing key/values pairs, with or without comparing constructor, prototype...)
0
Very good question Darío Estevanez
There are a couple of interesting things that your code highlights.
In JavaScript, some data types like strings and numbers are simple (primitive types) and others are more complex (often called object types). If you are checking equality on strings, such as "a" === "a", it returns true. The same is not true for objects, arrays and other types which fall into this more complex category.
So, if you make two objects like this (called object literals), and check their equality like this, it returns false:
{"letter": "a"} === {"letter": "a"}.
2nd part of answer coming up...
0
Here's a slight change to your code where I do two things differently.
1) I save the object to a variable and reuse that variable in both arrays and as the argument passed to the includes() in the first console.log()
2) I fix a slight syntax error you had in the second console.log() - you were missing the return keyword. When you use the curly braces - { } - in an ES6 arrow function, it returns undefined if you don't explicitly use the word return. This is why the second log showed false, because not every item in the array you were calling every() on was undefined. In fact, undefined wasn't present in your array at all.
const letterPair = {"a": "a"}
const arr = [letterPair]
const arr2 = [letterPair]
console.log(`includes(): ${arr.includes(letterPair)}`)
console.log(arr.every(i => {
return arr2.includes(i)
}))
Hopefully this code gives true for all your console logs.