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 ~~