Introduction to the $.inarray () method of jquery traversal array

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.