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?
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?
当数组仅包含字符串时,您正在检查整数。还要注意 jQuery 的inArray()
函数不像它的 PHP 对应函数那样工作。如果找到(作为整数),或者如果它不在数组中,它会返回值的实际从零开始的索引,而不是返回true
or 。false
-1
尝试这个:
if($.inArray('1', myObject) >= 0)
{
// Do your stuff.
}
这是一个jsFiddle 演示
或者你可以使用普通的 JS:
var x = ["1", "2", "1", "2"];
if (x.indexOf("1") !== -1) {
console.log("found");
} else {
console.log("not found");
}