In javascript,for the Array, why does:
console.log([1] == [1])
return false?
Is there any auto type-change in it? And [1] === [1]
return false too?
In javascript,for the Array, why does:
console.log([1] == [1])
return false?
Is there any auto type-change in it? And [1] === [1]
return false too?
Because two separate objects are never ==
(or ===
) to one another, even if they are equivalent (have the same properties with the same values). Arrays are objects.
To compare arrays, see this question's answers.
Because you are comparing two Array objects
.
If you want to compare the values of the arrays you can do :
console.log([1] == [1]);
console.log(compareTwoArray([1], [1]));
console.log(compareTwoArray([1], [2]));
function compareTwoArray(arr1, arr2) {
return arr1.length === arr2.length && arr1.every(x => arr2.includes(x));
}
Picture that you have a car, and your neighbour have the exact same car model.
If you want to strictly compare the cars, can you just look at the model? No, you will have to look at every part of the car (engine, wheels...) in order to say that they are "the same".
They are not one entity, this is two separated car, but to you, theirs characteristics make them identical.
So [1]
is an array, and [1]
and other array. But you would say they are identical if you look at theirs values.
In Javascript, Arrays are objects
typeof [1] // object
Which means when you write [1]
you're creating a new object. Since the objects aren't the same object, you can't test their equality with ==
or ===
.
See https://gomakethings.com/checking-if-two-arrays-are-equal/ for some ways to check array equality.
Comparing two objects even if they are identical to each other will return false regardless of whether you use ==
or ===
For comparing two objects use JSON.stringify(object)
conole.log(JSON.stringify([1])==JSON.stringify([1]))
This will return true
If you want multiple comparisons you can set JSON.stringify
to a variable :
let i = JSON.stringify
then you like this :
let i = JSON.stringify
conole.log(i([1]) == i([1]))
conole.log(i([1]) === i([1]))
Objects (Array are object) are not the same, you actually compare their addresses from the memory and since they are different instances, they are not equal.
btw, regarding primitives, you compare the actual values (not the address)