zoukankan      html  css  js  c++  java
  • 闭包实现add(1)(2), add(1,2)的功能

    function add(x, y) {
        // 当实参的数量大于等于2时,则此时返回前两个参数之和
        if (arguments.length >= 2) {
          return x + y;
        }
        // 当实参的数量为1时,此时返回一个带一个参数的匿名函数,当执行此匿名函数的时候返回外层和内部函数之和
        else if (arguments.length == 1) {
          return function (z) {
            return x + z;
          }
        }
        // 如果没有传参数时,则直接返回undefined
        else if (arguments.length == 0) {
          return undefined;
        }
      }
      // 执行结果检验
      console.log(add(1, 2)); // 3
      console.log(add(1)); //f(z)
      console.log(add(1)(3));
      console.log(add(1)(2)); // 3
      console.log(add(1, 2, 3, 4)); // 3
     
    //优化版本 使a(1)的时候输出的不是匿名函数
    function add(x, y) {
        // 当实参的数量大于等于2时,则此时返回前两个参数之和
        if (arguments.length >= 2) {
          return x + y;
        }
        // 当实参的数量为1时,此时返回一个带一个参数的匿名函数,当执行此匿名函数的时候返回外层和内部函数之和
        else if (arguments.length == 1) {
          function sum(b) {
            x = x + b
            return sum
          }
          sum.toString = function () {
            return x
          }
          return sum
        }
        // 如果没有传参数时,则直接返回undefined
        else if (arguments.length == 0) {
          return undefined;
        }
      }
      // 执行结果检验
      console.log(add(1, 2)); // 3
      console.log(add(1)); //1
      console.log(add(1)(3));  //4
      console.log(add(1)(2)); // 3
      console.log(add(1, 2, 3, 4)); // 3
     
    reduce方法实现累加
    // // add(1,2,3,4,5,6)
      // function add(...args) {
      //   return args.reduce((prev, val) => {
      //     return prev + val
      //   }, 0)
      // }
  • 相关阅读:
    适配iOS 10以及Xcode 8(转载)
    React-nwb的使用
    Android与JS混编(多图选择器)
    Android与JS混编(js调用android相机扫描二维码)
    Android与JS混编(js调用android相机)
    iOS: FFmpeg的使用
    UITableView/UICollectionView使用技巧
    IOS MapKit框架的使用(专门用于地图显示)
    iOS 地理编码 / 反地理编码
    iOS地图 -- 定位使用
  • 原文地址:https://www.cnblogs.com/memeflyfly/p/14236021.html
Copyright © 2011-2022 走看看