Why is an identical array not equivalent?

eg.

$  node
> [1, 2, 3] == [1, 2, 3]
false

Sorry if I misuse "identical" and "equivalent."

console.log([1, 2, 3] == [1, 2, 3]);
Run codeHide result

I ask because I'm used to languages ​​like Ruby

$  irb
irb(main):001:0> [1,2,3] == [1,2,3]
=> true

... or Python

$  python
>>> [1,2,3] == [1,2,3]
True

... where double equals compares the value of the expression

+4
source share
3 answers

Since they may have the same content, they do not point to the same link in memory.

For more accuracy, imagine the following example.

let arr1 = [1,2,3]
let arr2 = [1,2,3]
arr1 == arr2 //false

it makes sense because two arrays are different objects, even if they have the same value, for example, if we then did

arr1.push(4)

only arr1 will change.

, .

+4

. , .

, 3 , ? A B.

+3

[1,2,3] . , , . [1,2,3], , , . , , .

, , , == true. false.

As said more formally here :

Equality (==)

The equality operator converts the operands if they are not of the same type , and then applies strict comparison. If both operands are objects , then JavaScript compares internal references equal when the operands refer to the same object in memory.

+3
source

Source: https://habr.com/ru/post/1683280/


All Articles