Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"in" statement in Javascript/jQuery

Does Javascript or jQuery have sometime like the "in" statement in Python?

"a" in "dea" -> True

Googling for the word in is hopeless :(

like image 873
Christian Avatar asked Nov 28 '22 00:11

Christian


2 Answers

It does have an in operator but is restricted to object keys only:

var object = {
    a: "foo",
    b: "bar"
};

// print ab
for (var key in object) {
    print(key);
}

And you may also use it for checks like this one:

if ("a" in object) {
    print("Object has a property named a");
}

For string checking though you need to use the indexOf() method:

if ("abc".indexOf("a") > -1) {
    print("Exists");
}
like image 192
Ionuț G. Stan Avatar answered Dec 10 '22 01:12

Ionuț G. Stan


you would need to use indexOf

e.g

"dea".indexOf("a"); will return 2

If its not in the item then it will return -1

I think thats what you are after.

like image 23
AutomatedTester Avatar answered Dec 10 '22 01:12

AutomatedTester