I have 1 problem, why console.log ([200] == [200]) or console.log ([200] === [200]) all have false results, while 2 arrays have value same,.Help me, thanks you everyone .
For arrays (and objects btw) JS compares not vars values but pointers to its values in memory. In given example you have two different arrays in terms that they are two different objects of Array prototype and pointing to two different cells in memory.
== or === in JS works as you think only for primitive types, but Array is generally a particular case of Object and for objects == or === compares only vars poiters to values (as explained above).
Thats why (()=>{let a = [123], b=[123]; console.log(a==b, a===b);})(); will log false false and (()=>{let a = [123], b=a; console.log(a==b, a===b);})(); will log true true
To compare arrays you can use some workarounds:
1) Dummy one:
(() => {
let a = [123],
b = [123];
console.log(a.toString() == b.toString()); // true
console.log(a.toString() === b.toString()); // true
})();
2) A bit better one:
(() => {
let a = [123],
b = [123];
console.log(
a.length == b.length && a.every(function (v, i) {
return v == b[i];
})); // true
console.log(
a.length == b.length && a.every(function (v, i) {
return v === b[i];
})); // true
})();
3) The best one (IMO)(wrote for 5 minutes, so can contain issues):
Array.prototype.equals = function (array2, strict = true, deep = false) {
if (!(array2 instanceof Array)) {
throw Error('Array can be equaled only with Array');
} else if (this.length !== array2.length) {
return false;
}
deep = !!deep;
strict = !!strict;
return this.every((v, i) => {
if (v instanceof Array && deep) {
return array2[i] instanceof Array ? v.equals(array2[i], strict, deep) : false;
}
return strict ? v === array2[i] : v == array2[i];
});
};
(()=>{
let a = [123, [123, 321]],
b = ['123', ['123', '321']];
console.log(a.equals(b)); // false
console.log(a.equals(b, false)); // false
console.log(a.equals(b, true, true)); //false
console.log(a.equals(b, false, true)); //true
})();
Abinav Seelan
UI Engineer @Flipkart • https://abinavseelan.com 🙃
Hey!
Arrays in Javascript actually are just Objects.
When you do an equality check such as
object1 == object2, you aren't equating the properties in the objects, you're actually equating the references that these two objects are making.In your issue, the LHS and the RHS of the
==and===operators are actually pointing to two different references in memory, hence the result isfalse.It is for the same reason that the following happens,
var a = [200]; console.log(a == a); // true, since it's the same reference. console.log(a === a); // true, since it's the same referenceHope this answers your question! 😄