【发布时间】:2015-04-10 23:49:20
【问题描述】:
我正在研究一个计算表格,它生成一个具有两个值 [selection] 的多维数组,类似于:
[[10,0.5], [18,0.75]]
第二个数组 [lookup-table] 包含一系列值:
["10","0.5","0.1"], ["12","0.5","1.1"], ["14","0.5","3.1"], ["16", "0.5","5.1"],["18","0.5","7.1"], ["20","0.5","9.6"], ["22","0.5","11.6"] ... ["18","0.75","9.1"]
我正在尝试将 [selection] 数组中的索引 [0]、[1] 值与 [lookup-table] 数组中的相同索引值进行匹配。
["10","0.5","0.1"]... ["18","0.75","9.1"]
完成后,我想检索 [lookup-table] 中索引 [x][2] 值的值:
["10","0.5","0.1"]... ["18","0.75", "9.1"]
我确实在这里找到了一个非常有用且类似的问题:JavaScript - Compare two multidimensional arrays
并且在控制台中,它似乎可以正确识别数组索引中的匹配项。
我正在使用或多或少类似的功能:
function find(haystack, needles) {
var lookupValue = [];
//Iterate through all elements in first array
for(var x = 0; x < haystack.length; x++){
//Iterate through all elements in second array
for(var y = 0; y < needles.length; y++){
/*This causes us to compare all elements
in first array to each element in second array
Since haystack[x] stays fixed while needles[y] iterates through second array.
We compare the first two indexes of each array in conditional
*/
if(haystack[x][0] == needles[y][0] && haystack[x][1] == needles[y][1]){
console.log("match found");
console.log("Array 1 element with index " + x + " matches Array 2 element with index " + y);
//Retrieve the price for the high and low lookup values and store in array
lookupValue = haystack[x][2];
}
}
}
return lookupValue;
}
var totalResult = find(lookupTable, flushGrowthArray ).toString();
但是,当我尝试从 [lookup-table] 中的匹配项中检索 haystack[x][2] 索引值时,出于某种原因,我只返回了一个值。
我认为这可能是一个非常简单的错误;我究竟做错了什么?我感谢任何新的见解。
【问题讨论】:
-
您将
lookupValue替换为每个找到的匹配项,而不是将匹配项推送到数组中。 -
啊,有道理。以及我只检索检索到的最后一个值的原因。
标签: javascript arrays