簡體   English   中英

如何在JavaScript中的函數(本身就是一個參數)中傳遞參數

[英]How argument is being passed in the function(which itself is an argument) in JavaScript

我有一個關於JavaScript的非常基本的問題。 考慮以下代碼:

var numbers = [4,2,3,4,5,4,3,2,1];
var everyResult = numbers.every(function(item,index,array) {
    alert(arguments.length);
    return (item > 1);
});

現在,在上面的代碼中,我將匿名函數作為“每個”函數的參數傳遞。 我的匿名函數究竟如何精確地獲取3個參數(item,index,array)。

您傳遞的匿名函數只是作為對every()方法的參數提供的,該方法會多次調用它。 every()遍歷列表項,並每次使用以下三個參數調用匿名函數:value,index和整個數組。

以下是實際的every()函數如何工作的近似源代碼:

Array.prototype.every = function(callback) {
    for(i=0; i<this.length; i++) {
        callback(this[i], i, this);
    }
}

這實際上不是一個基本的javascript問題,而是一個庫問題,以及它如何“發生”取決於實現。

這是every javascript的示例實現:

function every(array, fn) {
    for(var i = 0; i < array.length; i++) {
        fn(array[i], i, array);
    }
}

您可以這樣稱呼它:

every([1,2,3,4], function(item, index, array) {
    // do stuff
});

如您所見,是every函數本身,它調用fn (這是您傳入的函數),並確定要傳遞的參數。

讓我們用回調參數構建一個簡單的函數:

function foo(callback)
{
    var callbackArgument = 'bar';
    callback(callbackArgument);
}

讓我們使用它:

foo(function(arg){
  console.log(arg);
}); // logs "bar" to the console!

我的匿名函數究竟如何精確地獲得3個參數(item,index,array)?

使用另一個示例,也許更容易理解:

var numbers = [4,2,3,4,5,4,3,2,1];
var everyResult = numbers.every(function(item,index,array) {
alert(arguments.length);
return (item > 1);
});

您還可以通過以下方式編寫相同的代碼:

var numbers = [4,2,3,4,5,4,3,2,1];
var everyResult = numbers.every(item,index,array) {

function anonymous(firstVar,secondVar,thirdVar){

//do your anonymous stuff here
alert(thirdVar.length);
return (firstVar > 1);

}

//get the anonymous function processed data
var anonymousFunctionResults = anonymous(item,index,array);

//do your original stuff that you would have done with the results of anonymous function
anonymousFunctionResults...
}
});

或以這種方式:

function anonymous(firstVar,secondVar,thirdVar){

//do your anonymous stuff here
alert(thirdVar.length);
return (firstVar > 1);

}

var numbers = [4,2,3,4,5,4,3,2,1];
var everyResult = numbers.every(item,index,array, anonymous) {

//get the anonymous function processed data
var anonymousFunctionResults = anonymous(item,index,array);

//do your original stuff that you would have done with the results of anonymous function
anonymousFunctionResults...
}
});

或以這種方式:

function anonymous(firstVar,secondVar,thirdVar){

//do your anonymous stuff here
alert(thirdVar.length);
return (firstVar > 1);

}

var numbers = [4,2,3,4,5,4,3,2,1];
var everyResult = numbers.every(anonymous(item,index,array)) {

//get the anonymous function processed data 
//you can use the "firstParameter" variable already of course 
//this is just to make a point
var anonymousFunctionResults = firstParameter;

//do your original stuff that you would have done with the results of anonymous function
anonymousFunctionResults...
}
});

如果我很了解您的問題:)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM