【问题标题】:Explain API function signature syntax [duplicate]解释 API 函数签名语法 [重复]
【发布时间】:2017-11-20 03:27:39
【问题描述】:

阅读文档几年了,我经常对解释函数签名时常用的语法感到困惑。例如:

来自Mozilla Array.map Docs:

var new_array = arr.map(callback[, thisArg])

文档列出了回调的三个参数:currentValue、index 和 array,但签名只是有这个奇怪的 callback[, thisArg] 语法。那个逗号是怎么回事?为什么“回调”旁边有数组括号?有没有关于这种语法的文档?这种语法有名字吗?任何帮助将不胜感激。

谢谢!

【问题讨论】:

    标签: javascript api syntax signature


    【解决方案1】:

    函数Array.prototype.map 需要一个函数作为第一个参数:

    var new_array = arr.map(callback[, thisArg])
    

    方括号表示第二个参数是可选的。您可以调用Array.prototype.map,带或不带第二个参数。两个函数调用都有效:

    var array = [1, 2, 3, 4];
    
    var myFunc = function (number) {
      return number * 5;
    };
    
    var myFuncUsingThis = function (number) {
      console.log(this);
      return number;
    };
    
    var myThisArg = {
      foo: 'bar'
    };
    
    console.log(array.map(myFunc));
    console.log(array.map(myFuncUsingThis, myThisArg));

    最后同

    console.log(array.map(myFuncUsingThis.bind(myThisArg)));
    

    因此,如果您提供给Array.prototype.map 的函数使用this 对象,则可以在Array.prototype.map 调用该函数时使用第二个(可选)参数指定该函数的this 对象。


    currentValueindexarray 是完全不同的东西。当您致电Array.prototype.map 时,您不必提供它们。相反,Array.prototype.map 为您提供了它们:它使用这三个参数调用您提供给它的函数(但您不必使用所有三个参数)。

    函数的第一个参数是当前正在处理的数组中元素的值,第二个参数是该元素的索引,第三个参数是数组本身。

    您可以编写一个使用索引参数的函数:

    var array = Array(20).fill(0); // an array containing 20 zeros
    
    var evenNumbers = array.map(function (number, index) {
      // number is zero, index is the index of the element we should transform
      return index * 2;
    });
    
    console.log(evenNumbers);

    如果您看一下Array.prototype.map 的(幼稚)实现,也许会有所帮助:

    Array.prototype.map = function (callback, thisArg) {
      // "this" is the array on which we work
    
      var arr = []; // the new array that we build
      var result;
      for (var i = 0; i < this.length; i += 1; i++) {
        result = callback.call(thisArg, this[i], i, this);
        arr[i] = result;
      }
      return arr;
    };
    

    【讨论】:

    • 很好的答案(和问题)++1
    【解决方案2】:

    括号内的参数表示它们是可选的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-12-10
      • 1970-01-01
      • 2013-09-03
      • 2015-07-29
      • 1970-01-01
      • 2018-06-29
      相关资源
      最近更新 更多