0

i have a object like:

["1", "2", "1", "2"]

No i want to check if "1" exists in object. I don't need to know how often it exists.

$.inArray(1, myObject) -> Returns always -1

So what is wrong or what i have to do?

4

2 回答 2

2

当数组仅包含字符串时,您正在检查整数。还要注意 jQuery 的inArray()函数不像它的 PHP 对应函数那样工作。如果找到(作为整数),或者如果它不在数组中,它会返回值的实际从零开始的索引,而不是返回trueor 。false-1

尝试这个:

if($.inArray('1', myObject) >= 0) 
{
    // Do your stuff.
}

这是一个jsFiddle 演示

于 2013-07-24T10:22:08.700 回答
2

或者你可以使用普通的 JS:

var x = ["1", "2", "1", "2"];

if (x.indexOf("1") !== -1) {
    console.log("found");
} else {
    console.log("not found");
}
于 2013-07-24T10:27:54.440 回答