Arrays are not identical after sorting even with identical values

前端 未结 2 1391
刺人心
刺人心 2021-01-29 13:38
var a = [1,2,3]
var b = a.sort();

console.log(\'a\',a,\'b\',b); // a [1,2,3] b [1,2,3]
console.log(a === b); // true

a = [1,3,2];
console.log(a.sort() === b) // false
         


        
相关标签:
2条回答
  • 2021-01-29 14:22

    Dont know very well which numbers are you using, but I guess you must use the optional parameter compareFunction: (you can read complete guide here)

    var arr = [ 40, 1, 5, 200 ];
    function comparar ( a, b ){ return a - b; }
    arr.sort( comparar );  // [ 1, 5, 40, 200 ]
    

    Because if you dont use it you will get this: (numbers ordered by unicode)

    var arr = [ 40, 1, 5, 200 ];
    arr.sort();  //[ 1, 200, 40, 5 ] 
    
    0 讨论(0)
  • When comparing two arrays the return value is true if they are referring to the same object. The values or the content of the arrays are not compared.

    0 讨论(0)
提交回复
热议问题