Reputation: 1564
I have a dictionary of strings to arrays of strings: {"a":["b", "c"]}
. When indexing into the dictionary, I get an array of strings back, but checking if any string is in this array always returns false.
Here is the code setup:
var dict = {
"first":["a", "b", "c"]
}
if("a" in dict["first"]){
// Never hits this line
console.log("Found a!");
}
I'm pretty new to Javascript so I may be missing something about the setup of a dictionary object, but it seems pretty straightforward and I have professional experience in a few C languages so it is fairly disconcerting that this doesn't work. What is wrong here?
Upvotes: 2
Views: 1202
Reputation: 115242
The in operator returns true if the specified property is in the specified object, Taken from here.
a
is not a property it's an array value, array index is act as property and 0 in dict["first"]
will be true
here. So here you can use indexOf()
var dict = {
"first": ["a", "b", "c"]
}
if (dict["first"].indexOf("a") > -1) {
console.log("Found a!");
}
Upvotes: 3
Reputation: 6866
try this. this will work to you.
var dict = {
"first":["c", "b", "a"]
};
console.log(dict.first);
for( var x in dict.first){
if(dict.first[x]=="a")
{
console.log("index of a :"+ x);
break;
}
}
}
Upvotes: 0