Why [] == [] is false in JavaScript?

前端 未结 6 1737
时光说笑
时光说笑 2020-12-03 17:32

I am working on a part of the code where I have an array which looks like [[data]]. The data is rendered on the server side through the Django temp

6条回答
  •  星月不相逢
    2020-12-03 18:12

    Because Arrays are reference type, meaning, if for example you make an array

    let a = [1,2,3,4,5];

    let b = a;

    the b is actually just a reference of array a, so if you compare them

    a===b is true,

    because they are basically link together.. So if you change something to array b it will also going to be change to array a,

    b[0] = "test";

    array a now is ["test",2,3,4,5];

    But if you do this this

    let a = [1,2,3,4,5];

    let b = a.slice(0);

    and then compare them

    a===b is false

    because now they are both different Arrays, meaning if you change the Array b, it will not affect the Array a

    b[0] ="hello";

    Array a is still [1,2,3,4,5]

    while array b is now ["hello",2,3,4,5]

    that is also what happen when you compare the []===[] is false

    Because basically what you are asking to JavaScript is if they are the same Array which is not

提交回复
热议问题