这篇文章将为大家详细讲解有关JavaScript中filter函数怎么用,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。
filter 函数
语法: var newArray = arr.filter(callbackFn(currentValue[, index[, array]])[, thisArg])
方法功能: 创建一个新数组, 其包含通过所提供函数实现的测试的所有元素。
返回:一个新的、由通过测试的元素组成的数组,如果没有任何数组元素通过测试,则返回空数组。
自定义函数:myFilter。
Array.prototype.myFilter = function(callbackFn, thisArg) {
if (typeof callbackFn !== 'function') throw ('callbackFn参数必须是函数');
let element = this,
len = element && element.length || 0,
result = [];
if (!thisArg) thisArg = element;
for (let index = 0; index < len; index++) {
if (callbackFn.call(thisArg, element[index], index, element)) result.push(element[index]);
}
return result;
};
关于“JavaScript中filter函数怎么用”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。