函数和回调 - JS

时间:2017-08-07 15:09:39

标签: javascript

我得到了三个函数,它们使用回调发送2个参数,但是我不理解代码,即使它有注释,我如何使用这些函数记录或操作数据或数组或对象。

// Define a function, each, which takes in a collection and 
// uses a callback on the elements of collection
// Collection can be either an array or an object
var each = function(collection, callback){
    if(Array.isArray(collection)){
        for(var i=0;i<collection.length;i++){
            callback(collection[i]);
        }
    }
    else{
        for(var key in collection){
            callback(collection[key]);
        }
    }
};


// Define a function, map, which uses a callback on a collection and returns an array
// example, times3 of the array, [3,6,9,12,15]
// Create an empty array and push the values from the callback 
// onto that array.  Then return the array

// You must use each function instead of a for-loop.
// Each element of collection will be passed as an argument into 
// the function parameter which then uses the call-back from the outer scope!

var map = function(collection, callback){
    var new_Array = [];
    each(collection, function(x){
           new_Array.push(callback(x));
    });
    return new_Array;
};


// Define a function filter, which checks the boolean value of the callback 
// on the element of collection
// output each boolean value of the callback
// example, even of an array, [1,2,3,4,5] -> false, true, false, true, false
var filter = function(collection, callback){
    each(collection, function(item){
        if(callback(item)){
            return item;
        }
   });
};

var myObj = {
  num1: 1,
  num2: 2,
  num3: [3, 5, 6]
};

var myArr = [2, 4, 6, 8, 9];

var output = each(myObj);
console.log(output);

有什么想法吗?任何人都可以解释(在外行的术语中)这些代码如何工作以及如何操纵它们?

1 个答案:

答案 0 :(得分:1)

在JavaScript中,您可以将函数作为参数传递给另一个函数。函数callbackeachmap接受的filter参数应该是函数,因为它们被称为函数。

我们以下面的函数为例:

function callWithFoo (callback) {
  callback('Foo');
}

我们定义了一个名为callWithFoo的函数,它接受一个名为callback的参数。它使用'Foo'调用该参数。

如果我们想使用callWithFoo,我们必须用函数调用它 - 我们必须给它一个函数作为参数:

function someFunction (arg) {
  console.log('I was called with:', arg);
}
callWithFoo(someFunction); // calls someFunction with 'Foo', which logs 
                           // 'I was called with: Foo'

我们作为参数传递给其他函数的函数通常称为回调函数。

现在你的函数each:它遍历我们给它的数组,对于数组中的每个元素,它用该元素调用回调函数:

function logIt (arg) { // logs its first argument to the console
  console.log(arg);
}
each([1, 2, 3, 4, 5], logIt); // logs 1, then 2, then 3, then 4, then 5

我们也可以传递一个匿名函数:

each([1, 2, 3, 4, 5], function (arg) {
  console.log(arg);
}); // logs 1, then 2, then 3, then 4, then 5

我确信你可以弄明白mapfilter做了什么。

顺便说一句,这些功能是Array.prototypeArray.prototype.forEachArray.prototype.mapArray.prototype.filter的一部分。