gpt4 book ai didi

JavaScript 过滤器 - 从 jQuery 过滤器回调方法返回什么?

转载 作者:行者123 更新时间:2023-12-03 03:21:37 26 4
gpt4 key购买 nike

无论调用过滤器方法后是否未使用应用于我的变量的过滤器结果,我需要从 jQuery 过滤器回调方法返回什么才能正确定义函数?

var results = [];
var filterResult = 0;

$(elem).each(function(){
results.push($(this).val().trim().toLowerCase())
});
var string = event.target.value.trim().toLowerCase();

results.filter(function (r) {
if(r == string)
filterResult = filterResult + 1;
return r; //<-- what needs to be returned for this callback to be properly defined
});

最佳答案

Array.prototype.filter通过将函数应用于现有数组的每个元素来创建一个新数组,并且仅当函数返回 true 时才包含该元素。

The reduce() method applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single value.

例如:

var arr = [-3,-2,-1,0,1,2,3];
var positive = arr.filter(function (num) {
return num > 0;
});
// num now contains: [1,2,3]

从您的代码片段来看,这似乎并不是您想要做的事情。相反,您似乎正在尝试从数组的元素中派生单个值。在这种情况下,您想要的是 Array.prototype.reduce :

var count = results.reduce(function (total, currentItem) {
if (currentItem == string) {
return total + 1;
} else {
return total;
}
}, 0);

第二个参数 (0) 是 total 的起始值。

关于JavaScript 过滤器 - 从 jQuery 过滤器回调方法返回什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46553339/

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