[英]Does JavaScript or jQuery have a function similar to Excel's VLOOKUP?
JavaScript或jQuery是否有一個函數返回一個數組的元素,該數組的索引等於另一個數組中給定值的位置? (我可以寫自己的,但我不想重新發明輪子。)
就像是:
function vlookup(theElement, array1, array2) {
$.each(array1, function(index, element) {
if (element === theElement)
return array2[index];
});
return null;
}
但是,嗯...在標准庫中。
也許這樣的事情?
Array.prototype.vlookup = function(needle,index,exactmatch){
index = index || 0;
exactmatch = exactmatch || false;
for (var i = 0; i < this.length; i++){
var row = this[i];
if ((exactmatch && row[0]===needle) || row[0].toLowerCase().indexOf(needle.toLowerCase()) !== -1)
return (index < row.length ? row[index] : row);
}
return null;
}
然后你就可以對雙數組使用它, 就像這樣
根據您的目的,您可以修改indexOf
以使兩個字符串首先小寫,因此比較不會因“foo”與“FOO”而失敗。 另請注意,如果index
超過行的長度,則返回整個行(可以通過修改: row);
輕松地將其更改為第一個元素(或其他: row);
一部分。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.