繁体   English   中英

JavaScript或jQuery是否具有类似于Excel的VLOOKUP的功能?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM