Precautions for inArray in jQuery _ jquery

Source: Internet
Author: User
This article mainly introduces the inArray method precautions in jQuery, and analyzes the precautions for inArray method variable judgment in jQuery in the form of examples, for more information about how to use the inArray method in jQuery, see the following section. We will share this with you for your reference. The details are as follows:

Jquery provides great convenience for web developers. The goal of this article is to remind everyone to carefully consider the inArray method in jquery.

As we all know, javascript is a weak type language. You can switch between the numeric and character types at Will (for example, 1 + "" = "1"). The topic is as follows:

One method of jquery, inArray (ele, array), is to determine whether ele exists in the array. The returned value is the subscript that this element first appeared in the array, and sometimes-1 is not returned.

For example:

var a = 1;var array = [1,2,3];var b = $.inArray(a, array);

B is equal to 0.

However, if a = "1"; is set at this time, run the following command:

b = $.inArray(a, array);

B is equal to-1. This will bring about a problem, because some people may only want to get this judgment: "1" = 1, the logical expression is actually in the javascript environment, the return is true,, in inArray, the returned value is false. Therefore, if an array contains non-object variables, especially when judging numbers, it is best to use the original method.

You can also use a regular expression for verification as follows:

var a = 1;var reg = new RegExp("(^"+a+",)|(^"+a+"$)|(,"+a+",)|(,"+a+"$)");var array = [1,2,3,4];reg.test(array.toString());// truea = "1";reg.test(array.toString());// true

Okay, that's all ~~

Related Article

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.