• 通过一个例子,总结下检测数组属性的N种方法


    判断arr数组里是否含有a,有a返回1;没有返回2
    var arr = [{a:1,b:2,c:3},{q:1,w:2,e:3},{s:4,g:5,i:9},{b:2,v:3,u:4}];

      检测属性的3种方法:1、in运算符 2、hasOwnProperty()  3、!= underfind

    1、用hasOwnProperty()  结合 for()、$.each()、array.forEach()等方法

    var arr = [{a:1,b:2,c:3},{q:1,w:2,e:3},{s:4,g:5,i:9},{b:2,v:3,u:4}];
    for(var i=0;i<arr.length;i++){
        if(arr[i].hasOwnProperty("a")){
                      console.log(1);
        }else{
              console.log(2);
       }
    }    
    
    jQuery.each()函数用于遍历指定的对象和数组
    
    $.each( object, callback )
     Object类型指定需要遍历的对象或数组
    callback  Function类型 指定的用于循环执行的函数
    
    
     var arr = [{a:1,b:2,c:3},{q:1,w:2,e:3},{s:4,g:5,i:9},{b:2,v:3,u:4}];
       $.each(arr,function(index,item){
           if(item.hasOwnProperty("a")){
                console.log(1);
         }else{
            console.log(2);
        }
    

    或者用for in
     $.each(arr,function(index,item){
    for(i in item){
    if(i=="a"){
    console.log(1);
    }else{
    console.log(2);
    }
    }
    })

    或者用 != underfind
     $.each(arr,function(index,item){
    if(item.a != undefined){
    console.log(1);
    }else{
    console.log(2);
    }
    })
     
    forEach()方法用于调用数组的每个元素,并将元素传递给回调函数。
    语法:array.forEach(function(currentValue,index,arr),thisValue);
    
    
     var arr = [{a:1,b:2,c:3},{q:1,w:2,e:3},{s:4,g:5,i:9},{b:2,v:3,u:4}];
    arr.forEach(function(index,item){
         if(item.hasOwnProperty("a"){
             console.log(1);
        }else{
          console.log(2);
        }
    
    })
    

      2、for in 结合 !=underfind

     var arr = [{a:1,b:2,c:3},{q:1,w:2,e:3},{s:4,g:5,i:9},{b:2,v:3,u:4}];
    for(o in arr){
      if(arr[o].a !=underfind){
        console.log(1);
      }else{
         console.log(2);
       }
    }
    

      

      

      

  • 相关阅读:
    IDEA与Eclipse
    解释器模式
    设计模式(十一)—— 策略模式
    设计模式(六)—— 装饰模式
    Java注解
    Spring源码阅读(二)—— AOP
    业务开发(八)—— Maven
    高性能MySQL笔记
    Java源码阅读(六)—— ReentrantLock
    业务开发(六)—— MyBatis框架
  • 原文地址:https://www.cnblogs.com/colorful-paopao1/p/9076959.html
Copyright © 2020-2023  润新知