我有一个关于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个参数(项目,索引,数组)。
答案 0 :(得分:0)
您传递的匿名函数只是作为每个()方法的参数提供,该方法多次调用它。 every()遍历列表项并每次使用三个参数调用匿名函数:value,index和整个数组。
以下是实际every()函数如何工作的近似源代码:
Array.prototype.every = function(callback) {
for(i=0; i<this.length; i++) {
callback(this[i], i, this);
}
}
答案 1 :(得分:0)
这不是一个基本的javascript问题,而是一个库问题,以及它“如何发生”取决于实现。
这是javascript中every
的示例实现:
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
(这是您传入的函数),并决定要传递的参数。
答案 2 :(得分:0)
让我们用回调参数构建一个简单的函数:
function foo(callback)
{
var callbackArgument = 'bar';
callback(callbackArgument);
}
让我们用它:
foo(function(arg){
console.log(arg);
}); // logs "bar" to the console!
答案 3 :(得分:0)
我的匿名函数究竟是如何获得正好3 参数(项目,索引,阵列)?
使用替代示例可能会更容易理解:
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...
}
});
如果我理解你的问题:)