admin管理员组文章数量:1315353
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? (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.
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? (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.
Share Improve this question asked Mar 2, 2011 at 19:17 isekaijinisekaijin 19.8k19 gold badges87 silver badges154 bronze badges 2- Your example doesn't look like the typical vlookup usage, but what's wrong with coding it yourself? – Brad Christie Commented Mar 2, 2011 at 20:04
- I dislike coding something I could code not. Since I'm such a sloppy idiot, I prefer using actually designed/tested standard libraries. – isekaijin Commented Mar 2, 2011 at 21:15
1 Answer
Reset to default 6Something 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 parison doesn't fail with "foo" vs "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);
portion.
本文标签: Does JavaScript or jQuery have a function similar to Excel39s VLOOKUPStack Overflow
版权声明:本文标题:Does JavaScript or jQuery have a function similar to Excel's VLOOKUP? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741975100a2408073.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论