indexOf为数组中存在的值返回-1

indexOf returns -1 for value that exists in array

本文关键字:返回 存在 数组 indexOf      更新时间:2023-09-26

我有一个定义如下的数组:

var numeric =  [{ Value: "0" }, { Value: "1" }, { Value: "2" }, { Value: "3" }];

我正在尝试确定这个数组中是否存在特定的值。我已经尝试了以下所有行,它们都返回-1

numeric.indexOf(1);
numeric.indexOf("1");
numeric.indexOf({Value: "1"});

假设我无法控制如何定义数组。如何确定某个值是否存在于这种特定类型的数组中?

您必须遍历数组并检查属性。

var numeric =  [{ Value: "0" }, { Value: "1" }, { Value: "2" }, { Value: "3" }];
var index=-1;
for(var i = 0; i<numeric.length; i++)
    if(numeric[i].Value === "2") { 
        index = i; 
        break; 
    }
console.log(index);

您可以使用循环遍历对象:

var numeric = [{
    Value: "0"
}, {
    Value: "1"
}, {
    Value: "2"
}, {
    Value: "3"
}];
for (var key in numeric) {
    var value = numeric[key];
    if (value.Value == "1") {
        console.log("ok");
    }
}

在@MattBurland评论之后,您也可以使用常规for

var numeric = [{
    Value: "0"
}, {
    Value: "1"
}, {
    Value: "2"
}, {
    Value: "3"
}];
for (var i = 0; i < numeric.length; i++) {
    var value = numeric[i];
    if (value.Value == "1") {
        console.log("ok");
    }
}

由于数字是一个数组,因此可以使用.findIndex():

var search = 1;
var found = numeric.findIndex(function(n) {return n.value == search});

finded将是值为==1的项的索引,如果未找到,则为-1。此处引用。

如果您需要布尔结果,最好使用.some():

var found = numeric.some(function(n) {return n.value == search;});

此处引用。请注意,较旧的浏览器不支持这两个功能。