console.log([2,6,10]>[2,10,0]);
Return true
, why?
Because their string representations are compared:
console.log( [2, 6, 10].toString(), [2, 10, 0].toString(), [2, 6, 10] > [2, 10, 0] );
Why then is
[1,1,1]
not identical and not equal to[1,1,1]
?
Why not equal? Equal to:
var a = [1,1,1]; var b = [1,1,1]; console.log(!(a > b) && !(a < b));
And how to compare them then?
Elementally.
[1,1,1]
not identical and not equal to [1,1,1]
? - doox911 9:31 pmconsole.log([0,0,0]===[0,0,0]); VM1467:1 false
console.log([0,0,0]===[0,0,0]); VM1467:1 false
- chrome console - doox911When comparing to> and <objects are reduced to primitives - in the case of arrays, these are strings, in which all elements of the array are listed separated by commas. Therefore, [2,6,10]>[2,10,0]
is the same as "2,6,10">"2,10,0"
, and the lines are compared lexicographically. The first 2 characters are 2,
are the same here, but then 6
and 1
are compared further - it is obvious that the first one is larger - that’s true.
If you want to compare arrays element by element, you need to write your own function that compares them in a loop.
PS: A little off topic, but can be useful .
This function will return the number (starting from 1) of the larger array and 0 if they are equal
function compareArrays(m1, m2) { for(let i=0; i<m1.length && i<m2.length; i++) { if(m1[i]>m2[i]){ return 1; } if(m1[i]<m2[i]){ return 2; } } if(m1.length>m2.length){return 1;} if(m1.length<m2.length){return 2;} if(m1.length==m2.length){return 0;} return false; } console.log(compareArrays([5,6,4], [5,10,0]));
Source: https://ru.stackoverflow.com/questions/953388/
All Articles