each和foreach的区别是什么,我一直忘了还有这一茬,现在把这个总结一下,以备后用。

1、foreach是js的原生方法;each是jq的方法;

  例如:

  var arr = ['mary','jack'];

  arr.foreach(function(item,index){

    console.log(item,index);    //mary,0   jack 1

  })

2、$.each() 与 $(select).each()之间的区别

  2.1、$.each() 可用于遍历任何的集合(无论是数组或对象),如果是数组,回调函数每次传入数组的索引和对应的值,方法会返回被遍历对象的第一参数。

      $(select).each() 主要专用于jquery对象的遍历, 

 

$.each() 

例子1:数组 索引-值

  var arr = ['marry',"jack","peter"];

  $.each(arr, function(index,item) {
    console.log(index,item);    //marry 0;  jack 1;  peter 2
  });

例子2:对象, 传出键-键值

  var person = {

    name:"liu",
    age:20,
  }

  $.each(person, function(key,value) {

    console.log(key,value);  //name liu; age 20
  });

例子3.return false 会退出$.each()循环,this指向数组

  var arr2 = [ "one", "two", "three", "four", "five" ];
  $.each(arr2, function() {
    console.log(this); //this 指向为数组的值,入one,two...
    $("#"+ this).text('Mine is' + this + '.');
    return (this != 'three')
  });

  var obj = { one:1, two:2, three:3, four:4, five:5 };
  $.each(obj,function (index,value) {
    $("#" + index).append(document.createTextNode('-' + value))
  })

  

posted on 2017-09-26 17:10  liumcb  阅读(1310)  评论(0编辑  收藏  举报