JavaScript 中 filter() 方法的作用是什么?
htmljavascriptprogramming scripts更新于 2024/2/7 0:12:17
JavaScript 数组 filter() 方法创建一个新数组,其中包含通过所提供函数实现的测试的所有元素。
以下是参数 −
callback − 用于测试数组每个元素的函数。
thisObject − 执行回调时用作 this 的对象。
您可以尝试运行以下代码来了解如何在 JavaScript 中使用 filter() 方法 −
示例
<html>
<head>
<title>JavaScript Array filter Method</title>
</head>
<body>
<script>
if (!Array.prototype.filter) {
Array.prototype.filter = function(fun /*, thisp*/) {
var len = this.length;
if (typeof fun != "function")
throw new TypeError();
var res = new Array();
var thisp = arguments[1];
for (var i = 0; i < len; i++) {
if (i in this) {
var val = this[i]; // in case fun mutates this
if (fun.call(thisp, val, i, this))
res.push(val);
}
}
return res;
};
}
function isBigEnough(element, index, array) {
return (element >= 10);
}
var filtered = [12, 5, 8, 130, 44].filter(isBigEnough);
document.write("Filtered Value : " + filtered );
</script>
</body>
</html>
相关文章
有用资源
html 参考教程 - 该教程包含有关 html 的更多信息:https://www.cainiaomax.com/html/

