JavaScript數組過filter()方法創建一個新的數組提供的函數來實現測試的所有元素。
語法
array.filter(callback[, thisObject]);
下麵是參數的詳細資訊:
-
callback : 函數用來測試數組的每個元素
-
thisObject : 對象作為該執行回調時使用
返回值:
返回所創建數組
相容性:
這種方法是一個JavaScript擴展到ECMA-262標準;因此它可能不存在在標準的其他實現。為了使它工作,你需要添加下麵的腳本的頂部代碼:
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;
};
}
例子:
<html>
<head>
<title>JavaScript Array filter Method</title>
</head>
<body>
<script type="text/javascript">
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>
這將產生以下結果:
Filtered Value : 12,130,44
