[Javascript] JQuery $.each与$().each区别, for in 与 for of 区别

1. $.each()]与$().each()区别

  • $.each用于遍历数组、对象、数组对象, 代码形式 (arr,function(index,value)) (obj, function(key, value) {})
  • $().each用于遍历dom, 代码形式如$(‘li’).each(function() { var var xxx = this.xxx})
  • demo
<!DOCTYPE html>
<html>
<head>
<script src="/jquery/jquery-1.11.1.min.js">
</script>
<script>

$(function() {
  // 对象
    var a = {"name": 'Lucky', age: 12, sayName: function() { alert(this.name)}};

   // 数组
    var b = ["Day",2,3];

   // 对象数组
    var c = [];
    c.push(a);

    $.each(b, function(index, value) {
       console.log(index + ":" + value);
    });

    $.each(a, function(key, value) {
      console.log(key + "==" + value);
    });

    $.each(c, function(index, e) {
        console.log(index + "===" + e.name);
    });

    // dom, 也可这么写function(index, e) {$(e).text()}
    $('p').each(function() {
        console.log($(this).text());
    });

});

</script>
</head>
<body>
<p>如果您点击我,我会消失。</p>
<p>点击我,我会消失。</p>
<p>也要点击我哦。</p>
</body>
</html>

2. for in 与 for of区别

  • for in能遍历数组与对象的可枚举属性,但是不仅遍历对象内部,而且会遍历原型链(若只遍历对象内部,配合obj.hasOwnProperty(【属性】))
  • for of,(ES6增加)能遍历数组,但是不能遍历对象(ES6遍历对象内部可用Symbol.iterator)
  • demo
var a = {"name": 'Lucky', age: 12, sayName: function() { alert(this.name)}};
    var b = ["Day",2,3];
    var ele; 

    for (ele in a) {
         console.log(ele +':' +  a[ele]); //输出属性名称及属性值
    }
   for (ele in b) {
         console.log(ele + ':' + b[ele]);//输出属性名称及属性值
    }


   for (ele of b) {
         console.log(ele);  //输出数组属性值
    }
    /*报错:VM3258 v.asp:19 Uncaught TypeError: a[Symbol.iterator] is not a function(…)*/
    for (ele of a) {
         console.log(ele +':' +  a[ele]);
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值