定義和用法
filter() 方法創建一個新的數組,新數組中的元素是通過檢查指定數組中符合條件的所有元素。
注意: filter() 不會對空數組進行檢測。
注意: filter() 不會改變原始數組。
語法
array.filter(function(currentValue,index,arr), thisValue)
參數說明
參數 | 描述 | ||||||||
---|---|---|---|---|---|---|---|---|---|
function(currentValue, index,arr) | 必須。函數,數組中的每個元素都會執行這個函數 函數參數:
|
||||||||
thisValue | 可選。對象作爲該執行回調時使用,傳遞給函數,用作 "this" 的值。 如果省略了 thisValue ,"this" 的值爲 "undefined" |
具體實現
// 實現filter
Array.prototype.filter = function(fn, value){
if (typeof fn !== "function") {
return false;
}
var arr = this;
var temp = [];
for (var i = 0; i < arr.length; i++) {
var result = fn.call(value, arr[i], i, arr);
if (result) temp.push(arr[i]);
}
return temp;
}
測試
var arr = ["a", "bb", "ccc", 100, 2222, 3111];
console.log(arr.filter(function(item){
return typeof item === "string"
}));
console.log(arr.filter(function(item){
return typeof item === "number"
}));