gpt4 book ai didi

javascript - 这个函数的参数是怎么传递的?

转载 作者:行者123 更新时间:2023-11-30 14:59:48 24 4
gpt4 key购买 nike

做课本练习,其中:

let arr = [1, 2, 3, 4, 5, 6, 7];

function inBetween(a, b) {
return function(x) {
return x >= a && x <= b;
};
}

alert( arr.filter(inBetween(3, 6)) ); // 3,4,5,6

教科书还指出 filter 语法为:

let results = arr.filter(function(item, index, array) {
// should return true if the item passes the filter
});

所以我不完全理解 inBetween(a,b) 函数是如何工作的...就像这一行:

arr.filter(inBetween(3,6))

在我看来aitem参数,bindex参数中,但是显然这不是它的工作方式...有人可以分解这种语法以及它为什么工作吗?

最佳答案

所以 filter 方法接受一个应该返回 true 或 false 的函数,无论是否保留该项目。

在这个例子中,不是在过滤器内部编写该函数,而是在外部编写并传入。但是您仍然可以这样想:

let results = arr.filter(function(item, index, array) {
return item >= 3 && item <= 6;
});

在过滤器外部定义 inBetween 的原因是您可以传入值而不是像上面那样将它们硬编码到过滤器中。

当您调用 inBetween(3,6) 时,返回的是:

function(x) {
return x >= 3 && x <= 6;
}

像上面那样然后放入过滤器(只是没有 index/array 参数,因为它们不需要:

let results = arr.filter(function(x) {
return x >= 3 && x <= 6;
});

关于javascript - 这个函数的参数是怎么传递的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46720204/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com