The $.inarray () function searches the array for the specified value and returns its index value. Returns 1 if the value does not exist in the array;
The $.inarray (Value,array)--value is the value to look for, and the array is the one being looked up.
Use the $.inarray () method must pay attention to the point, otherwise it will fall out of the pit
(1) Look at the following code:
$ (function () { var arr=[{"name": "Zhang San"},{"name": "John Doe"},{"name": "Harry"}]; Alert ($.inarray ({"name": "Zhang San"}, arr); });
The above code does not carefully analyze how to see it is not wrong, but the return value is-1. Below to analyze the cause of the discovery:
The cause of the error is {"name": "Zhang San"} and {"name": "Zhang San"} is two different references, so {"name": "Zhang San"} is not found in arr array; If you change that, you can.
$ (function () { var obj = {"Name": "Zhang San" }; var arr = [{"Name": "John Doe"}, obj, {"name": "Harry"}]; Alert ($.inarray (obj, arr); });
This code returns 1; The return value is normal;
(2) It is known that JavaScript is a weakly typed language, and for numeric types and character types, you can switch freely (for example: 1+ "" = "1"), so there is the following code:
$ (function () { var arr = [1, 2, 3, 4, 5];
var a = 2;
Alert ($.inarray (A, arr); });
This code returns a normal value of 1;
$ (function () { var arr = [1, 2, 3, 4, 5]; var a = "2"; Alert ($.inarray (A, arr); });
When you change the value of a to a string 2 The return value is 1; So when you use this $.inarray () method, make sure that the data type is the same, although JavaScript is a weakly typed language;
Description of the $.inarray () method of the jquery traversal array