Previous Function 如何将其结果传递给回调

How Previous Function passes its result to callback

我正在尝试了解回调在这种情况下的工作原理。

例如给定此代码:

var images = jQuery.map((1234567 + '').split(''), function(n) {
  return '<img src="' + n + '.png" />'
})

一个匿名函数作为回调传入,但 'n' 如何在每次拆分后神奇地填充?它如何传递到 n 参数中?我的意思是我不认为 split 会把它的值注入 n..它怎么知道这样做的?

让我们再举一个例子,但这一次,我们显式将参数传递给回调函数

function randomGenerator(min, max, callback)
{
   var myNumber = Math.floor(Math.random() * (max - min + 1)) + min;
   setTimeout(function() { callback(myNumber); }, 500);
}

这非常简单,很明显 myNumber 是如何连接(显式传递)到 callback() 的;

问题是在我的第一个示例中,它是如何隐含地这样做的?我的意思是我是否可以假设 map() 在幕后发生的事情比我知道的要多得多?也许我必须深入研究 jQuery 库中 Map() 的实现,我猜……或者是否有一些关于隐式赋值在 JS 中如何工作的常识?

这就是 .map() 函数的作用。 .split() 调用只是构建数组,.map() 将迭代该数组。

传递给 .map() 的函数为数组中的每个元素(第一个参数)调用一次。每次调用都使用三个参数:数组中元素的值;元素的 index 和数组本身。您的匿名函数只有一个参数(这很常见),所以这就是元素值。

您指定了带有参数 "n" 的签名的匿名函数。 map 函数在内部调用匿名函数,为参数 "n" 提供具体对象。如果你删除参数它将不起作用

为数组中的每个元素调用指定的映射函数。字符串只是一个字符数组。

函数是与 JavaScript 中的任何其他对象一样的对象。您可以将它们作为参数传递给其他函数,然后其他函数可以为所欲为。

function do_something_with_two_numbers(something, num1, num2) {
    return something(num1, num2); 
}

function add(a,b) { return a + b };
function subtract(a,b) { return a - b };

alert(do_something_with_two_numbers(add, 2, 1));
alert(do_something_with_two_numbers(subtract, 2, 1));

MDN has a polyfill 作为 map:

的完整示例
// Production steps of ECMA-262, Edition 5, 15.4.4.19
// Reference: http://es5.github.io/#x15.4.4.19
if (!Array.prototype.map) {

  Array.prototype.map = function(callback, thisArg) {

    var T, A, k;

    if (this == null) {
      throw new TypeError(' this is null or not defined');
    }

    // 1. Let O be the result of calling ToObject passing the |this| 
    //    value as the argument.
    var O = Object(this);

    // 2. Let lenValue be the result of calling the Get internal 
    //    method of O with the argument "length".
    // 3. Let len be ToUint32(lenValue).
    var len = O.length >>> 0;

    // 4. If IsCallable(callback) is false, throw a TypeError exception.
    // See: http://es5.github.com/#x9.11
    if (typeof callback !== 'function') {
      throw new TypeError(callback + ' is not a function');
    }

    // 5. If thisArg was supplied, let T be thisArg; else let T be undefined.
    if (arguments.length > 1) {
      T = thisArg;
    }

    // 6. Let A be a new array created as if by the expression new Array(len) 
    //    where Array is the standard built-in constructor with that name and 
    //    len is the value of len.
    A = new Array(len);

    // 7. Let k be 0
    k = 0;

    // 8. Repeat, while k < len
    while (k < len) {

      var kValue, mappedValue;

      // a. Let Pk be ToString(k).
      //   This is implicit for LHS operands of the in operator
      // b. Let kPresent be the result of calling the HasProperty internal 
      //    method of O with argument Pk.
      //   This step can be combined with c
      // c. If kPresent is true, then
      if (k in O) {

        // i. Let kValue be the result of calling the Get internal 
        //    method of O with argument Pk.
        kValue = O[k];

        // ii. Let mappedValue be the result of calling the Call internal 
        //     method of callback with T as the this value and argument 
        //     list containing kValue, k, and O.
        mappedValue = callback.call(T, kValue, k, O);

        // iii. Call the DefineOwnProperty internal method of A with arguments
        // Pk, Property Descriptor
        // { Value: mappedValue,
        //   Writable: true,
        //   Enumerable: true,
        //   Configurable: true },
        // and false.

        // In browsers that support Object.defineProperty, use the following:
        // Object.defineProperty(A, k, {
        //   value: mappedValue,
        //   writable: true,
        //   enumerable: true,
        //   configurable: true
        // });

        // For best browser support, use the following:
        A[k] = mappedValue;
      }
      // d. Increase k by 1.
      k++;
    }

    // 9. return A
    return A;
  };
}

阅读 documentation for JQuery 地图,特别是它谈论回调的部分。

在 JavaScript 中,可以使用任意数量的参数调用函数,无论它是如何定义的。所以在 jquery.map 的定义中,它调用提供的回调 n 次,其中 n 是数组中元素的数量,并且在每次调用中传递两个参数,第一个是对象形式的数组元素,第二个是数组中项目的索引,它是一个整数。

如果您只想从零参数函数生成一个长度为 n 的新数组,您的回调在技术上可以有零参数。

var images = jQuery.map((1234567 + '').split(''), function(n) {
  return '<img src="' + n + '.png" />'
})

您有这段代码:(1234567 + '')。它将数字转换为字符串。然后 split('') 将拆分数组项中的所有数字。为每个项目调用回调函数,n 将获取数组中的每个值。 $.map 的本质是在原始数组的项目之上保存任何回调 return。 在这种情况下,您将拥有一个类似于 ["1","2","3","4","5","6","7"] 的数组。在你 运行 地图之后,你将得到图像数组

images=[
        '<img src="1.png" />',
        '<img src="2.png" />',
        '<img src="3.png" />',
        '<img src="4.png" />',
        '<img src="5.png" />',
        '<img src="6.png" />',
        '<img src="7.png" />'
    ]