2

I want to check if "foo" exists in the array named "Array", but $.inArray always returns -1. Why does it return -1 and how do I solve this?

Here is my code in a jsFiddle:

var Array = []
Array.push({'test':'fuu','url':'sdfsdfsdf'});
Array.push({'test':'qsgbfdsbgsdfbgsfdgb','url':'sdfssffbgsfdbgdfsdf'});
if($.inArray('fuu',Array) != -1) alert('present');
else alert('absent');
alert($.inArray('fuu',Array));
Uyghur Lives Matter
  • 18,820
  • 42
  • 108
  • 144
Random78952
  • 1,520
  • 4
  • 26
  • 36

2 Answers2

3

'fuu' is not actually in the array, it's a value of an object inside of the array. I'm afraid that you need a more complex check. I would also not use Array as the variable name as that's the name of the Array object, but apparently it's not a reserved word? not sure.

var arr = [];
...
var found = false;
$.each(arr, function () {
   if (this.test === 'fuu') {
      found = true;
      return false;
   }
});
if (found) alert('present');
Explosion Pills
  • 188,624
  • 52
  • 326
  • 405
3

You are pushing a Hash onto the Array

Array.push({'test':'fuu','url':'sdfsdfsdf'});

and then testing for a String.

$.inArray('fuu',Array)

If you add Array.push('fuu') then your test for present will work.

digidigo
  • 2,534
  • 20
  • 26