[英]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. 我尝试创建一个函数,但无法使其正常工作,对此我仍然很陌生。
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.