如何在两个数组元素中找到更大的数字比较

时间:2015-12-01 07:25:10

标签: javascript jquery

我有两个动态数组,可以像

arr1 = [4, 17, 12, 11];
arr2 = [11, 10, 23, 11];

现在我需要始终在#cal-box-1-1上保存较大的数字,在#cal-box-1-2上保存较小的数字,以从较大的数字中扣除较小的数字

for (i = 1; i < arr1.length; i++) { 
   $(".map").append('<div class="mapper"><div id="cal-box-1-'+i+'"></div><div id="cal-box-1-'+i+'"></div></div>");
}

3 个答案:

答案 0 :(得分:3)

如果您总是想从最高数字中减去较低的数字,可以执行以下操作:

var result = Math.abs(value1 - value2);

2中哪一个是最高值无关紧要:

10 - 7 === 3;      // Correct order
Math.abs(3) === 3;  // Value doesn't change.

7 - 10 === -3;     // Wrong order,
Math.abs(-3) === 3; // But Math.Abs fixes that.

-7 - -10 === 3;    // Correct order (-10 is smaller than -7)
Math.abs(3) === 3;  // Value doesn't change.

-10 - -7 === -3;   // Wrong order,
Math.abs(-3) === 3; // But Math.Abs fixes that.

因为您总是从最高值中减去最低值,所以总是得到>= 0的结果。

答案 1 :(得分:1)

确定哪个数字更大或更小的代码怎么样:

for (i = 0; i < arr1.length; i++) { // I assume you want to start with the first element
   var bigger = Math.max(arr1[i], arr2[i]);
   var smaller = Math.min(arr1[i], arr2[i]);
}

答案 2 :(得分:0)

您是要求找到最大数字和最小数字然后减去两个?

public class ShowCamera extends Activity implements SurfaceHolder.Callback {