Matching a value to JSON array values in jquery
I have a JSON array that looks like this:
['Monkey','Cheetah','Elephant','Lizard','Spider']
I also have a text input. I want to test whether the value of the input upon 'blur' is also in the array and if it is do something.
Knowing a bit of python I tried something like this:
var 开发者_如何学编程existing_animals = ['Monkey','Cheetah','Elephant','Lizard','Spider']
$('input').blur(function() {
user_animal = $(this).val()
if (user_animal in existing_animals) {
alert('Animal already exists!')
}
});
So, how rookie is my mistake?
The in
operator checks if a key is present in a dictionary (object). It however does now work for arrays. The right approach is to use jQuery.inArray:
if ($.inArray(user_animal, existing) > -1) {
alert('Animal already exists!')
}
in
is for checking if an object includes the attribute, where-as you're using an array.
If you want to use your in
, you can do:
var existing_animals = {
"Monkey":1,
"Cheetah":1
};
etc, then all will be fine using in
, however, it would be better to continue using your Array, and simply loop over it.
$('input').blur(function() {
user_animal = $(this).val()
for (var i=0;i<existing_animals.length;i++) {
if (existing_animals[i] == user_animal) {
alert("Animal exists");
break;
};
};
});
The ECMA 5th edition introduces an indexOf
method for Arrays, so it should be as easy as doing:
if (existing_animals.indexOf(user_animal) != -1) {
alert("Animal exists");
};
However, IE doesn't support this; you can implement it yourself though.
If you want to use the "in" keyword in JS, this might be helpful: Reduce multiple ORs in IF statement in Javascript
I believe you might find your answer in this article.
Since the JSON evaluates to an array, you should be looking at the indexOf
function. Not sure why you mentioned python here..
精彩评论