JS中如何判断数组中是否包含某一元素

JavaScript014

JS中如何判断数组中是否包含某一元素,第1张

可以直接使用数组的indexOf方法来判断,如果元素存在于数组中,那么返回元素在数组中的下标值,如果不存在,那么返回-1,但是该方法在某些版本的IE中是不起作用,所以建议使用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

}

1. 判断表单元素是否存在(一)if("periodPerMonth" in document.theForm){return true}else{return false}2. 判断页面元素是否存在if(document.getElementById("XXX")){//存在}3. 判断表单元素是否存在(二)if(document.theForm.periodPerMonth){//存在}或if(typeof(document.theForm.periodPerMonth)=="object"){//存在} 4. 判断表单是否存在if(document.theForm){//存在}5.用Jquery写脚本if ( $("#someID").length >0 ) {$("#someID").text("hi")} 6.判断div下是否有a元素<script>window.onload=function(){var obj = document.getElementById("sc2")var a = obj.getElementsByTagName("a")if(a.length>0) alert("有a")else alert("无a")}</script><div class="tabcontent" id="sc2"><a href="#">About Us </a><a href="#">What do we do? </a>