zoukankan      html  css  js  c++  java
  • 通过一个例子,总结下检测数组属性的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);
       }
    }
    

      

      

      

  • 相关阅读:
    python pandas库和stats库计算偏度和峰度(附程序)
    python matplot 字体配置-中文手绘漫画风格
    流密码
    信息安全和密码学基础知识
    剑指offer48-把字符串转换成整数
    剑指offer47-不用加减乘除做加法
    剑指offer46-求1+2+...+n
    剑指offer45-孩子们的游戏
    剑指offer44-扑克牌顺子
    剑指offer43-翻转单词顺序列
  • 原文地址:https://www.cnblogs.com/colorful-paopao1/p/9076959.html
Copyright © 2011-2022 走看看