[英]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.