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

时间:2011-03-02 19:17:53

标签: javascript jquery

JavaScript或jQuery是否有一个函数返回一个数组的元素,该数组的索引等于另一个数组中给定值的位置? (我可以写自己的,但我不想重新发明轮子。)

类似的东西:

function vlookup(theElement, array1, array2) {
    $.each(array1, function(index, element) {
        if (element === theElement)
            return array2[index];
    });
    return null;
}

但是,嗯...在标准库中。

1 个答案:

答案 0 :(得分:6)

或许这样的事情?

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;
}

然后你可以对双数组like so

使用它

根据您的目的,您可以修改indexOf以使两个字符串首先小写,因此比较不会因“foo”与“FOO”而失败。另请注意,如果index超过行的长度,则返回整行(通过修改: row);部分,可以轻松将其更改为第一个元素(或其他)。

相关问题