gpt4 book ai didi

Javascript 数组浏览和比较

转载 作者:行者123 更新时间:2023-11-29 10:30:13 25 4
gpt4 key购买 nike

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

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

三个值的最大值=45

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

三个值的最大值=40

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

三个值的最大值=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

最佳答案

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

该提案的特点是 Array#maparrow functionsMath.maxspread syntax ...用于将其作为参数的数组。

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

console.log(max);

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);

关于Javascript 数组浏览和比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48171141/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com