如何回调函数的功能

时间:2015-06-09 09:12:56

标签: javascript jquery

我有以下代码

$.map( [ 0, 1, 2 ], function( n ) {
  return n > 0 ? n + 1 : null;
});  
  

Out Put:[2,3]

我知道$.map Translate all items in an array or object to new array of items.Documentation) 我想知道call back function中的.map如何运作(内部实施)? 一个可能的答案可能是

  1. .map有一些循环将数组的每个元素传递给call back method,返回一些值。
  2. .map管理call back method的每个值返回。在这种情况下,推入一些内部数组。
  3. 循环结束.map返回数组 的修改
  4.   

    但我不确定它是如何工作的,它是否像我解释的那样有效?

2 个答案:

答案 0 :(得分:2)

  

但我不确定这是怎么回事?

是的,基本上它是如何运作的。正如the source code 一样,完整的详细信息(该行号会随着时间的推移而腐烂......)。目前,它看起来像这样:

map: function( elems, callback, arg ) {
    var value,
        i = 0,
        length = elems.length,
        isArray = isArraylike( elems ),
        ret = [];

    // Go through the array, translating each of the items to their new values
    if ( isArray ) {
        for ( ; i < length; i++ ) {
            value = callback( elems[ i ], i, arg );

            if ( value != null ) {
                ret.push( value );
            }
        }

    // Go through every key on the object,
    } else {
        for ( i in elems ) {
            value = callback( elems[ i ], i, arg );

            if ( value != null ) {
                ret.push( value );
            }
        }
    }

    // Flatten any nested arrays
    return concat.apply( [], ret );
},

答案 1 :(得分:2)

嗯,没有比查看源代码更好的检查方法

function (elems, callback, arg) {
    var value, i = 0,
        length = elems.length,
        isArray = isArraylike(elems),
        ret = [];

    // Go through the array, translating each of the items to their new values
    if (isArray) {
        for (; i < length; i++) {
            value = callback(elems[i], i, arg);

            if (value != null) {
                ret.push(value);
            }
        }

        // Go through every key on the object,
    } else {
        for (i in elems) {
            value = callback(elems[i], i, arg);

            if (value != null) {
                ret.push(value);
            }
        }
    }

    // Flatten any nested arrays
    return concat.apply([], ret);
}
  1. 是的,无论是Array版本还是对象,它是循环播放并调用callback来设置值
  2. 是的,对于两个循环,值为推送
  3. 是的,它通过调用concat
  4. 返回展平的数组