Home > Web Front-end > JS Tutorial > How to determine whether a value exists in a jquery array

How to determine whether a value exists in a jquery array

藏色散人
Release: 2023-01-04 09:36:39
Original
3039 people have browsed it

The jquery array method to determine whether a value exists: first create an HTML sample file; then use the "$.inArray("Element (String)", array name)" method to find the specified value in the array, and Just return its index value.

How to determine whether a value exists in a jquery array

The operating environment of this tutorial: windows7 system, jquery1.10.0 version, Dell G3 computer.

Recommended: "jquery video tutorial" "javascript basic tutorial"

To determine whether an array contains an element, from the principle In other words, it is to traverse the entire array and then determine whether it is equal

Jquery method

You can use the method provided by Jquery: use $.inArray() to judge.

inArray() function is used to find the specified value in the array and return its index value (if not found, return -1)

$.inArray("元素(字符串)",数组名称)
Copy after login

When the element (string) exists , returns the subscript of the element in the array, returns -1 if it does not exist

Example:

<!DOCTYPE>
<html>
<head>
<title>jquery判断值是否存在于数组中</title>
<meta charset="utf-8">
</head>
<body>
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
<script>
//参数第一个为数组,第二个为需要判断是否存在于数组中的值
function isInArray(arr,val){
  var str = ","+arr.join(",")+",";
  if(str.indexOf(","+val+",") != "-1"){
    //该数存在于数组中
    arr.splice($.inArray(val,arr),1);  //把该数从数组中删除
    console.log(arr);
  }else{
    //该数不存在于数组中
    console.log("不存在");
  }
}
var arr = [1,28,60,80,6];
isInArray(arr,28);//存在,删除元素28
isInArray(arr,18);//不存在,提示“不存在”
</script>
</body>
</html>
Copy after login

Rendering:

How to determine whether a value exists in a jquery array

js method

var arr = ["a", "b", "c"];
// js arr.indexOf("c")
var result1 = arr.indexOf("c"); //返回index为2
Copy after login

Custom method

var arr = ["a", "b", "c"];
// 自定义 contains(arr, "c")方法
function contains(arr, obj) {
    //while
    var i = arr.length;
    while(i--) {
        if(arr[i] === obj) {
            return i;
        }
    }
    return -1;
}
var result1 = contains(arr, "c"); //返回index为2
Copy after login

The above is the detailed content of How to determine whether a value exists in a jquery array. For more information, please follow other related articles on the PHP Chinese website!

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