[英]Javascript array Browse and compare
I need to browse and compare two array and get the following result : For example: 我需要浏览并比较两个数组并获得以下结果:例如:
T = [5,10,15];
V = [15,50,30];
I need to return the following values: 我需要返回以下值:
V[0]-T[0] = 15-5 = 10
V[1]-T[0] = 50-5 = 45
V[2]-T[0] = 30-5 = 25
V[0]-T[1] = 15-10 = 5
V[1]-T[1] = 50-10 = 40
V[2]-T[1] = 30-10 = 20
V[0]-T[2] = 15-15 = 0
V[1]-T[2] = 50-15 = 35
V[2]-T[2] = 30-15 = 15
The MAX of the three value = 35 三个值的MAX = 35
I tried to do it by myself using this code: 我尝试使用此代码自己完成:
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'); }
But i get the following result: 但我得到以下结果:
10
45
25
25
5
40
20
20
0
35
15
15
You could map t
and take the maximum value of the mapped values of the subtraction. 您可以映射t
并获取减法的映射值的最大值。
This proposal features Array#map
with arrow functions and Math.max
with spread syntax ...
for an array for taking it as parameters. 该提议的特点是带有箭头函数的 Array#map
和带扩展语法的 Math.max
...
用于将其作为参数的数组。
var t = [5, 10, 15], v = [15, 50, 30], max = t.map(tt => Math.max(...v.map(vv => vv - tt))); console.log(max);
ES5 ES5
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.