简体   繁体   中英

Javascript Compare values in 2 arrays

What would be a shorter way to write :

if (array1[0] >= array2[0] && array1[1] >= array2[1] && ...) {
do something;
}

I tried creating a function but I was not able to make it work, I'm still quite new at this.

The most elegant way would be to use .every

The every() method tests whether all elements in the array pass the test implemented by the provided function.

if (array1.every(function(e,i){ return e>=array2[i];})) {
    do something;
}
var isGreater = true;
for (var i = 0; i < array1.length; i++)
{
    if (array1[i] < array2[i])
    {
        isGreater = false;
        break;
    }
}

if (isGreater)
{
    //do something
}

You loop your first array and replace the numbers by the looping variable (i)

This will return true if all elements of a are greater than all elements of b . It will return as early as possible rather than having to compare all of the elements.

function compare(a, b) {
  for (i = 0; i < a.length; i++) {
      if (a[i] < b[i]) { return false;}
  }
  return true
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM