[英]Does JavaScript or jQuery have a function similar to Excel's VLOOKUP?
Do JavaScript or jQuery have a function that returns the element of an array whose index equal to the position of a given value in another array? JavaScript或jQuery是否有一个函数返回一个数组的元素,该数组的索引等于另一个数组中给定值的位置? (I could write my own, but I don't want to reinvent the wheel.)
(我可以写自己的,但我不想重新发明轮子。)
Something like: 就像是:
function vlookup(theElement, array1, array2) {
$.each(array1, function(index, element) {
if (element === theElement)
return array2[index];
});
return null;
}
But, um... in the standard library. 但是,嗯...在标准库中。
Something like this perhaps? 也许这样的事情?
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;
}
Then you can use it against a double array, like so 然后你就可以对双数组使用它, 就像这样
Depending your purpose, you can modify the indexOf
to make both strings lowercase first so the comparison doesn't fail with "foo" vs "FOO". 根据您的目的,您可以修改
indexOf
以使两个字符串首先小写,因此比较不会因“foo”与“FOO”而失败。 Note also that if index
exceeds the row's length, the entire row is returned (this can be changed to the first element (or whatever) easily by modifying the : row);
另请注意,如果
index
超过行的长度,则返回整个行(可以通过修改: row);
轻松地将其更改为第一个元素(或其他: row);
portion. 一部分。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.