简体   繁体   English

Javascript比较2个数组中的值

[英]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 最优雅的方法是使用.every

The every() method tests whether all elements in the array pass the test implemented by the provided function. every()方法测试数组中的所有元素是否通过提供的函数实现的测试。

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) 您循环第一个数组,并用循环变量(i)替换数字

This will return true if all elements of a are greater than all elements of b . 如果所有元素这将返回真正的a比的所有元素更大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
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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