zoukankan      html  css  js  c++  java
  • javascript闭包使用 分类: JavaScript 2015-05-01 11:34 652人阅读 评论(3) 收藏

    之前看到一段代码,很是不能理解,然后就查找资料并且找网络上得大牛请教,最后弄懂了这段代码,然后就拿出来总结一下。

    1.挖坑

    先来看一段代码:

    var arrTest = [];
    for (var i = 0; i < 3; i++) {
        //注意函数没有传参数进入函数体
        arrTest.push(function () {
            console.log('>>>' + i);
        })
    }
    
    //arrTest=[function(){console.log('>>>'+i)}, function(){console.log('>>>'+i)}, function(){console.log('>>>'+i)}]
    
    console.log(arrTest[0].toString());  //function(){console.log('>>>',+i)}
    console.log(i);
    console.log('-------------');
    //长度可以使用l 简单的单词来代替,减小代码长度
    for (var i = 0, arrLength = arrTest.length; i < arrLength; i++) {
        console.log(i);
        arrTest[i]();
    }
    
    
    //验证的i的值
    console.log('i的值是' + i);     //i=3
    
    console.log('end for');
    for (var j = 0, arrLength = arrTest.length; j < arrLength; j++) {
        console.log(j);
        arrTest[j]();
    }
    
    arrTest = [function () { console.log('>>>' + i) }, function () { console.log('>>>' + i) }, function () { console.log('>>>' + i) }]
    

    结果是这个样子的:
    这里写图片描述

    那怎么实现当遍历整个函数的时候打印出我们所希望的0,1,2这样的结果呢?

    /*
    对函数进行改造,当执行循环的时候,打印0,1,2
     */
    var arrTest1 = [];
    for (var i = 0; i < 3; i++) {
        //构造一个立即执行的函数将函数的返回结果添加入数组中
        (function(n) {
            arrTest1.push(function() {
                console.log('>>>' + n);
            });
        })(i);
    }
    console.log(arrTest1);
    for (var i = 0, l = arrTest1.length; i < l; i++) {
        arrTest1[i]();
    }

    打印结果:
    这里写图片描述

    版权声明:本文为博主原创文章,未经博主允许不得转载。

  • 相关阅读:
    dhcp服务配置
    配置一台时间服务器
    创建kvm虚拟机
    实现跳板机
    双向同步使用unison
    17、 Shell脚本题:编写个shell脚本将当前目录下大于10K的文件转移到/tmp目录下。
    find 命令
    权限管理:建立一个经理组
    使用sudo命令
    [转]tftp在put上传的时候显示File not found的解决办法
  • 原文地址:https://www.cnblogs.com/yisuowushinian/p/4715606.html
Copyright © 2011-2022 走看看