[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]);
    }
阅读更多
换一批

没有更多推荐了,返回首页