简体   繁体   中英

Find value or check if value exists in object

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?

You're checking for an integer, when the array contains only strings. Also be advised that jQuery's inArray() function does not act like its PHP counterpart. Rather than returning true or false , it returns the actual zero-based index of the value if found (as an integer), or -1 if it isn't in the array.

Try this:

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

Here's a jsFiddle demo

Or you can use plain JS:

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

if (x.indexOf("1") !== -1) {
    console.log("found");
} else {
    console.log("not found");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM