Home > Web Front-end > JS Tutorial > Analysis of precautions for inArray method in jQuery_jquery

Analysis of precautions for inArray method in jQuery_jquery

WBOY
Release: 2016-05-16 15:18:08
Original
1497 people have browsed it

This article analyzes the precautions for the inArray method in jQuery. Share it with everyone for your reference, the details are as follows:

jquery provides great convenience for web developers. The purpose of writing this article is to remind everyone to be careful about the inArray method in jquery.

Everyone knows that JavaScript is a weakly typed language. You can switch between numeric types and character types at will (for example: 1+""="1"). Let’s start with the topic:

A method inArray(ele, array) of jquery is to determine whether ele exists in the array. The return value is the subscript of the first time the element appears in the array. If not, it returns -1.

For example:

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

Copy after login

At this time, b is equal to 0.

However, if a="1"; is set at this time, then execute it again:

b = $.inArray(a, array);
Copy after login

At this time, b is equal to -1. This will cause a problem, because some people may only want to get this judgment: "1" == 1. This logical expression is actually in the JavaScript environment and returns true. However, in inArray, the returned value is true. false, so if an array stores non-object variables, especially when judging numbers, it is best to use the original judgment method.

You can also use regular expressions to verify as follows:

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

Okay, that’s all~~

Readers who are interested in more content related to jQuery arrays can check out the special topic on this site: "Summary of jquery array usage"

I hope this article will be helpful to everyone in jQuery programming.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template