zoukankan      html  css  js  c++  java
  • js中判断数组中是否包含某元素的方法

     原文:https://blog.csdn.net/weixin_37569048/article/details/80587975

    js中存在一个数组,如何判断一个元素是否存在于这个数组中呢,首先是通过循环的办法判断,代码如下:

    复制代码
    var arr = ['a','s','d','f'];
    console.info(isInArray(arr,'a'));//循环的方式
    
    /**
     * 使用循环的方式判断一个元素是否存在于一个数组中
     * @param {Object} arr 数组
     * @param {Object} value 元素值
     */
    function isInArray(arr,value){
        for(var i = 0; i < arr.length; i++){
            if(value === arr[i]){
                return true;
            }
        }
        return false;
    }
    复制代码

    这种方式是比较通用的一种方式,但是需要自己写函数,下面看一下第二种方式:

    var arr = ['a','s','d','f'];
                    console.info(arr.indexOf('a'));//在IE某些版本中不支持,可以自行扩展

    这种方式是直接使用数组的indexOf方法来判断,如果元素存在于数组中,那么返回元素在数组中的下标值,如果不存在,那么返回-1,注意indexOf是区分大小写的,字母O必需大写,不然是会报错的,另外,该方法在某些版本的IE中是不起作用的,因此在使用之前需要做一下判断,修改后的代码如下所示:

    复制代码
    /**
     * 使用indexOf判断元素是否存在于数组中
     * @param {Object} arr 数组
     * @param {Object} value 元素值
     */
    function isInArray3(arr,value){
        if(arr.indexOf&&typeof(arr.indexOf)=='function'){
            var index = arr.indexOf(value);
            if(index >= 0){
                return true;
            }
        }
        return false;
    }
    复制代码

    第三种方式,就是使用jquery的inArray方法,该方法返回元素在数组中的下标,如果不存在与数组中,那么返回-1,代码如下所示:

    复制代码
    /**
     * 使用jquery的inArray方法判断元素是否存在于数组中
     * @param {Object} arr 数组
     * @param {Object} value 元素值
     */
    function isInArray2(arr,value){
        var index = $.inArray(value,arr);
        if(index >= 0){
            return true;
        }
        return false;
    }
    复制代码

    这种方式可以用来删除一个数组中的未知下标值的元素,代码如下所示:

    var arr = ['a','s','d','f'];
    console.info("删除元素之前的数组:"+arr);
    arr.splice($.inArray('a',arr),1);
    console.info("删除元素之后的数组:"+arr);

    执行结果是:

    [Web浏览器] "删除元素之前的数组:a,s,d,f"    /test/index.html (12)
    [Web浏览器] "删除元素之后的数组:s,d,f"  /test/index.html (14)
  • 相关阅读:
    17.1.2.1 Advantages and Disadvantages of Statement-Based and Row-Based Replication
    17.1.2 Replication Formats
    Setting the Master Configuration on the Slave
    17.1.1.9 Introducing Additional Slaves to an Existing Replication Environment
    17.1.1.8 Setting Up Replication with Existing Data
    17.1.1.7 Setting Up Replication with New Master and Slaves
    17.1.1.6 Creating a Data Snapshot Using Raw Data Files
    列出display的值,并说明它们的作用
    CSS设置DIV居中
    CSS选择符有哪些?哪些属性可以继承?优先级算法如何计算?
  • 原文地址:https://www.cnblogs.com/zhang1f/p/12486240.html
Copyright © 2011-2022 走看看