开发者

jQuery: question about inArray()

开发者 https://www.devze.com 2023-02-18 04:04 出处:网络
I have this code below. I don\'t know why inArray() doesn\'t output 0. Any idea? var client = new Array();

I have this code below. I don't know why inArray() doesn't output 0. Any idea?

var client = new Array();

function removeClient(id){

  alert(id);    //prints 17
  alert(client);   //prints 17
  alert(typeof(id));  //this prints "number"
  alert(typeof(client));  //this prints "object"
  alert($.inArray(id, client));   //this prin开发者_如何转开发ts "-1", why?

}

Regards

Javi


You probably populated the array with the string '17' and not the number 17. That's why it returns -1.

Live demo: http://jsfiddle.net/simevidas/s4Q3K/


$.inArray returns -1 when an element is not found. Can we see where you are filling client with array values? You might not be filling the array correctly.

alert(client) should not print '17' it should print the array values separated by commas.

EDIT: I figured out what may the the issue. If client contains the string '17' and not the number 17, because 17 !== '17'

Example: http://jsfiddle.net/ub6xX/1/

Working example: http://jsfiddle.net/fkling/ub6xX/


Because inArray(id, client) checks whether id is in the array client.

And since id is not in that array (at least not per your sample), it returns -1. Know your API.


-1 means not found, so basically the id does not exist in the items of the array.

0 would mean that it had found the id at the first position of the array. Nothing in your code suggests that this should happen.

http://api.jquery.com/jQuery.inArray/


The $.inArray() method is similar to JavaScript's native .indexOf() method in that it returns -1 when it doesn't find a match. If the first element within the array matches value, $.inArray() returns 0.

Because JavaScript treats 0 as loosely equal to false (i.e. 0 == false, but 0 !== false), if we're checking for the presence of value within array, we need to check if it's not equal to (or greater than) -1.


I don't see where you you are putting the id into the client array in your exmaple I'm guessing because you don't have it in there in array can't find it

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号