zoukankan      html  css  js  c++  java
  • 刷题-函数-闭包-返回函数

    刷了两道题,函数比我想象的要有意思。

    第一题,返回函数

    //输入
    functionFunction('Hello')('world')
    
    //返回
    hello,world

    这种问题,我第一次遇到,实际上都是多个参数搞定,见识少了点。记录一下。

    我是直接看的答案,因为我不会,思索也没有头绪。

    看到的答案有两种。

    第一:假设传入的,不知道怎么形容。参数?还是函数?姑且叫他参数吧,假设传入的参数就是是2个。

    使用闭包就可以解决

    function functionFunction(str) {
      var f = function(s){
            return str + "," + s;  
        }  
        return f  
    }

    functionFunction('hello')('world')
    //返回
    hello,world

    或者

    function functionFunction(str) {
      return function(s){
          return str + ', ' +s   
        }  
    }
    functionFunction('hello')('world')
    //返回
    hello,world

    第二种接受不确定数量的参数:

    function functionFunction(str) {
      var ret = Array.prototype.slice.call(arguments).join(',');
      var temp = function(str){
       ret = [ret,Array.prototype.slice.call(arguments).join(',')].join(',');
       return temp;      
      };
      temp.toString = function(){
       return ret;    
      }  
      return temp      
    }
    
    //输出:1, 2, 3, 4
    functionFunction(1)(2)(3,4).toString();

    //在函数中,

    arguments 其实就是传递进来的参数。
    arguments对象是所有(非箭头)函数中都可用的局部变量

    Array.prototype.slice.call(arguments)能将具有length属性的对象转成数组,除了IE下的节点集合(因为ie下的dom对象是以com对象的形式实现的,js对象与com对象不能进行转换)

    只要知道功能就好,刚刚学习,深入也深入不了哪去。。。

    第一次进来,arguments 的lenth是1,值也是1。

    这时候借助闭包,temp 以后,往里面传入参数都用他接受,这个时候temp的方法toString 返回ret。最终返回temp

    这么说可能没明白


    我们把代码分成块来看。
    //这是第一块
    
    var ret = Array.prototype.slice.call(arguments).join(',');
    
    //这是第二块,这里面引用了第一块的内容 ret
    
    var temp = function(str){
        ret = [ret,Array.prototype.slice.call(arguments).join(',')].join(',');
        return temp;      
    };
    
    //第三块
    temp.toString = function(){
        return ret;    
    }
    
    //第四块
    return temp
    正常情况下,1234按照步骤走的。
    如果多个参数,那么
    在第二块的时候,ret 被从新赋值了,因为调用的是ret,这个时候ret的值已经被改变。那么temp最终的值也会做相应的改变。
    写之前有点没有搞懂,写的过程好像有一点明白。
    感冒吧,脑子不清楚,写的也不是很清楚,先记录下来。
    其实一般情况只要掌握了,传入两个参数使用闭包,就可以了


  • 相关阅读:
    Poj2104-K-th Number(主席树)
    Poj3237-Tree(树链剖分)
    Spoj QTREE(树链剖分)
    字符串算法
    网络流算法
    利用DiDiSoft OpenPGP Library for .NET 程序加密解密文件
    利用GPG4Win加密解密文件
    .NET Standard和.NET Framework的区别【转】
    Aras学习笔记 (6) Aras Client Side代码弹出标准ItemType内容窗口
    WebClient使用DownloadFile下载文件超时的解决办法
  • 原文地址:https://www.cnblogs.com/damai/p/8744755.html
Copyright © 2011-2022 走看看