如何使用javascript检查数组中是否存在值

时间:2015-04-30 15:20:24

标签: javascript arrays indexof

我有一个表格形式的数组:

"localValues" : [
    {
        "localValId" : "8KfbEozjdQYAefuHF",
        "localProductCode" : "291105300",
        "localMarkupVal" : "2.8",
        "localMembersPrice" : "3344"
    },
    {
        "localValId" : "qdCY6Kkvc7e8m4yxw",
        "localProductCode" : "291105300234",
        "localMarkupVal" : "2.8432",
        "localMembersPrice" : "3344333"
    },
    {
        "localValId" : "i827Eve8zBexRSTSP",
        "localProductCode" : "291105300",
        "localMarkupVal" : "2.8432",
        "localMembersPrice" : "899"
    }

我正在尝试返回localProductCode的位置:

var a = localValues;

var location = a.indexOf('291105300');

console.log('location: ' + location)

然而,这会返回-2,这是不正确的,因为该代码确实存在于数组中。有人可以帮忙吗?提前谢谢!

4 个答案:

答案 0 :(得分:1)

数组不包含'291105300'

不是直接搜索String,而是需要为给定的键找到具有该值的对象:

function hasMatch(array, key, value) {
  var matches = array.filter(function(element) {
    return element[key] === value;
  });

  return (matches.length > 0);
}

hasMatch(localValues, 'localProductCode', '291105300') // true

答案 1 :(得分:1)

console.log(JSON.stringify(localValues).indexOf('291105300') != -1 ? true : false);

答案 2 :(得分:0)

以下代码将找到您要查找的值的索引。如果值不在数组中,则返回-1。取自this SO post。我刚刚在最后添加了警报。

var myArray = [0,1,2]可能会成为var myArray = localValues;,然后您可以将needle设置为您要查找的值。



var indexOf = function(needle) {
    if(typeof Array.prototype.indexOf === 'function') {
        indexOf = Array.prototype.indexOf;
    } else {
        indexOf = function(needle) {
            var i = -1, index = -1;

            for(i = 0; i < this.length; i++) {
                if(this[i] === needle) {
                    index = i;
                    break;
                }
            }

            return index;
        };
    }

    return indexOf.call(this, needle);
};

var myArray = localValues,
    needle = 3,
    index = indexOf.call(myArray, needle); // 1
    alert(index);
&#13;
&#13;
&#13;

编辑:有点迟到,您可能正在寻找阵列中的KEY。

&#13;
&#13;
function GetObjectKeyIndex(obj, keyToFind) {
    var i = 0, key;
    for (key in obj) {
        if (key == keyToFind) {
            return i;
        }
        i++;
    }
    return null;
}

// Now just call the following

GetObjectKeyIndex(localValues, "localProductCode");
&#13;
&#13;
&#13;

上面的代码段会返回一个ID(如果存在),如果找不到具有此类名称的密钥,则返回null

答案 3 :(得分:0)

要返回找到该值的所有索引的数组,您可以使用mapfilter

function findValue(data, key, value) {
    return data.map(function (el, i) {
        return el[key] === value
    }).map(function (el, i) {
        return el === true ? i : null
    }).filter(function (el) {
        return el !== null;
    });
}

findValue(data.localValues, 'localProductCode', '291105300'); // [0, 2]

DEMO