简体   繁体   中英

jquery.inArray() function not working

I am having a array as follows

       var nameIDHashMap = [];
       nameIDHashMap.push({
            key: name,
            value: xmlLength
       });
     startToEnd.push({
          key: $(this).attr("startFrom"),
          value: $(this).attr("endTo")
    });

I m trying to use the inArray() function like shown below

            var variablestart = startToEnd[0].key;
            alert("The variable Start is :"+variablestart);
            var toEnd;
            if(jQuery.inArray(variablestart,nameIDHashMap) > -1) {
                alert('found');
            }
            if ($.inArray(variablestart, nameIDHashMap) != -1) 
            {
                alert("Found");
            //  toEnd = startToEnd[connectWindow].value
            }
            else
                alert("Fail");

I dont know why always the else loop is called. None of the if loop is getting called. Both of the array has that same key present. Please let me know where I am doing wrong.Thanks!

variablestart is a property of an element in the array, not an element in the array.

var nameIDHashMap = [];
nameIDHashMap.push({
    key: 'foo',
    value: 'bar'
});

$.inArray(nameIDHashMap[0].key, nameIDHashMap); // this is not an element, -1
$.inArray(nameIDHashMap[0], nameIDHashMap); // this is an element, 0

You are essentially trying to equate the object { key: 'foo', value: 'bar' } to the string 'foo' , which are not equal.

http://jsfiddle.net/jbabey/kgYSe/

That's not how .inArray() works. It searches for an array element that's equal to the value you pass in. It doesn't have any provisions for a comparison function.

Even if it did work, what you're assembling there isn't a "hash table". If you want to do efficient lookups by key, you can just create named properties on a simple object:

var map = {};
map.someKey = someValue;

The .inArray() method and anything like it performs a linear-time search through the array, and that's not a very efficient way to do things if you're going to have an "interesting" number of key/value pairs.

edit — if you really must keep a linear unindexed list of named properties, you could use a lookup function like this:

function find( list, key, test ) {
  test = test || function(e) { return e ? e.key == key : false; };

  for (var i = 0; i < list.length; ++i)
    if (test(list[i])) return i;
  return -1;
}

To use that, you'd just do:

if (find(nameIDHashMap, someKey) >= 0) {
  alert("Found!");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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