Edit: The link provided below by faintsignal is the most applicable answer. It not only explains why this behavior occurs but offers a solution to the stated problem.
I've got an array that I would like to determine if all elements are equal to a single value. The following code seems like it should work, but it doesn't. Can anyone explain?
var array1 = ['foo', 'bar', 'baz'];
var array2 = ['foo', 'foo', 'foo'];
//I expect this to be false and it is
new Set(array1) == new Set(['foo']);
//I expect this to be true and it is not
new Set(array2) == new Set(['foo']);
Any information would be most welcome!
Check if the size of the set is one:
new Set(array2).size === 1
As other answers/comments have already mentioned,
new Set(array2) == new Set(['foo'])
returns false because different objects are not equal.
You could in theory check for the equivalence of new Set(array2)
and new Set(['foo'])
using the techniques in questions referred to in the comments, but you don't need to do this, since checking if the size is 1 does exactly what you need.
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.