Javascript数组浏览和比较

时间:2018-01-09 15:09:27

标签: javascript

我需要浏览并比较两个数组并得到以下结果: 例如:

T = [5,10,15];
V = [15,50,30];

我需要返回以下值:

V[0]-T[0] = 15-5 = 10
V[1]-T[0] = 50-5 = 45
V[2]-T[0] = 30-5 = 25

三值的MAX = 45

V[0]-T[1] = 15-10 = 5
V[1]-T[1] = 50-10 = 40
V[2]-T[1] = 30-10 = 20

三值的MAX = 40

V[0]-T[2] = 15-15 = 0
V[1]-T[2] = 50-15 = 35
V[2]-T[2] = 30-15 = 15

三个值的MAX = 35

我尝试使用此代码自行完成:

var T = [5,10,15];
var V = [15,50,30];
var X;
for (var i = 0; i < T.length; ++i){
    for (var j = 0; j <  V.length; ++j)
	{
		X = V[j]-T[i];  	
		console.log(V[j]-T[i]); 
	}
	if ((V[j]-T[i]) >= X)
	{
		X = V[j]-T[i];
		console.log(V[j]-T[i]);
	}
    else
    {
        console.log(X); 
	}		  
	console.log('\n');
}

但我得到以下结果:

10
45
25
25
5
40
20
20
0
35
15
15

1 个答案:

答案 0 :(得分:3)

您可以映射t并获取减法的映射值的最大值。

此提案包含Array#map arrow functionsMath.max spread syntax ...的数据,用于将其作为参数。

&#13;
&#13;
var  t = [5, 10, 15],
     v = [15, 50, 30],
     max = t.map(tt => Math.max(...v.map(vv => vv - tt)));

console.log(max);
&#13;
&#13;
&#13;

ES5

&#13;
&#13;
var  t = [5, 10, 15],
     v = [15, 50, 30],
     i, j,
     max,
     result = [];

for (i = 0; i < t.length; i++) {
    max = v[0] - t[i];                    // take the first value of v
    for (j = 1; j < v.length; j++) {      // iterate from the second value of v
       max = Math.max(max, v[j] - t[i]);  // get max value
    }
    result.push(max);                     // store max
}

console.log(result);
&#13;
&#13;
&#13;