zoukankan      html  css  js  c++  java
  • each和foreach的区别

    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))
      })

      

  • 相关阅读:
    JDK1.5新特性
    mysql的基本使用
    IO简单示例
    序列化
    策略模式
    div+css布局之流体浮动布局
    xp优化
    Junit所使用的设计模式
    SSH使用总结(annotation配置方式)
    hibernate3.6.0使用总结
  • 原文地址:https://www.cnblogs.com/liumcb/p/7597770.html
Copyright © 2011-2022 走看看