$each()方法使用

$.each()函数:可以遍历对象和数组
遍历对象:回调函数中的两个参数,分别是对象的属性和对应的属性值$.each(collection,callback(key,value))
遍历数组:回调函数中的两个参数,分别是数组的下标和内容$.each(collection,callback(index,value))
举例:
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>$each遍历</title>
  <script type="text/javascript" src="js/jquery-3.2.1.min.js"></script>
</head>
<body>
</body>
  <script>
    $(function() {
      var arr=[{'name':'tom','age':20},{'name':'jack','age':18}];
      //遍历数组对象
      $.each(arr, function(index,element) { //index = 0, element = {name: "tom", age: 20}
        //debugger;
        alert(index);
      });

      //遍历数组
      var array=[4,'tom',true];
      $.each(array, function(index,value) { //index = 0, value = 4
        //debugger;
        alert(index);
      });

      //遍历对象
      var ele={'name':'tom','age':20};
      $.each(ele, function(key,value) { //key = "name", value = "tom"
        debugger;
        alert(key);
      });
    })
  </script>
</html>

posted @ 2020-09-09 10:08  懂得归零  阅读(586)  评论(0)    收藏  举报