我想制作一个JavaScript算法,将Flight1的值与其余两个值进行比较,然后将Flight 2与Flight 1和Flight 3进行比较。
结果应该类似于dif_flight1_flight2 = 10,dif_flight1_flight3 = 110。
var x = [
['flight1', '190'],
['flight2', '200'],
['flight3', '300']
]
答案 0 :(得分:0)
存储您的变量,然后根据值计算差异。 Google如何在JS中访问/遍历2D数组。
details.component.ts
答案 1 :(得分:0)
您可以这样做:
var x = [
['flight1', '190'],
['flight2', '200'],
['flight3', '300']
];
var result = [];
for(let i = 1; i < x.length; i++) {
let value = parseInt(x[0][1]) - parseInt(x[i][1]);
let element = 'diff_' + x[0][0] + '_' + x[i][0];
result.push({
key: element,
value: Math.abs(value)
});
}
此算法采用第一个元素,并将其与其他N -1个元素进行比较。在结果数组上,您拥有所有差异。
一个问题:为什么使用数组而不是对象数组?
答案 2 :(得分:0)
每个值都必须与每个值进行比较
function test_dif(){
var x = [
['flight1', '190'],
['flight2', '200'],
['flight3', '300']
];
var result = [];
for(let i = 0; i < x.length; i++) {
for(let c = 0; c < x.length; c++){
let value = parseInt(x[c][1]) - parseInt(x[i][1]);
let element = 'diff_' + x[c][0] + '_' + x[i][0];
result.push({
key: element,
value: Math.abs(value)
});
}
}
return result;
}
结果:
0: {key: "diff_flight1_flight1", value: 0}
1: {key: "diff_flight2_flight1", value: 10}
2: {key: "diff_flight3_flight1", value: 110}
3: {key: "diff_flight1_flight2", value: 10}
4: {key: "diff_flight2_flight2", value: 0}
5: {key: "diff_flight3_flight2", value: 100}
6: {key: "diff_flight1_flight3", value: 110}
7: {key: "diff_flight2_flight3", value: 100}
8: {key: "diff_flight3_flight3", value: 0}