简体   繁体   English

查找值或检查对象中是否存在值

[英]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. 不,我想检查对象中是否存在“ 1”。 I don't need to know how often it exists. 我不需要知道它多久出现一次。

$.inArray(1, myObject) -> Returns always -1 $.inArray(1, myObject) ->始终返回-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. 还应注意,jQuery的inArray()函数的行为不像其PHP对应函数。 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. 而不是返回truefalse ,它返回值的实际从零开始的索引(如果找到)(作为整数),或者返回-1如果不在数组中)。

Try this: 尝试这个:

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

Here's a jsFiddle demo 这是一个jsFiddle演示

Or you can use plain JS: 或者您可以使用普通的JS:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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