We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
filter() 方法创建一个新数组, 其包含通过所提供函数实现的测试的所有元素。
参数
var newArray = arr.filter(callback(element[, index[, array]])[, thisArg])
callback 用来测试数组的每个元素的函数。返回 true 表示该元素通过测试,保留该元素,false 则不保留。它接受以下三个参数
thisArg(可选) 执行 callback 时,用于 this 的值
返回值:一个新的、由通过测试的元素组成的数组,如果没有任何数组元素通过测试,则返回空数组。
Array.prototype.filter2 = function(callback, thisArg){ if(this === undefined || this === null){ throw new TypeError("Cannot read property 'filter' of null or undefined") } if(Object.prototype.toString.call(callback) !== "[object Function]"){ throw new TypeError(callback + " is not a function") } let O = Object(this),len = O.length >>> 0; let result = new Array(); for(let k=0;k<len;k++){ if(k in O){ let status = callback.call(thisArg, O[k], k, O); if(status){ result.push(O[k]) } } }; return result; } var arr = [ { id: 15 }, { id: -1 }, { id: 0 }, { id: 3 }, { id: 12.2 }, { }, { id: null }, { id: NaN }, { id: 'undefined' } ]; var invalidEntries = 0; function isNumber(obj) { return obj !== undefined && typeof(obj) === 'number' && !isNaN(obj); } function filterByID(item) { if (isNumber(item.id) && item.id !== 0) { return true; } invalidEntries++; return false; } var arrByID = arr.filter2(filterByID); console.log('Filtered Array\n', arrByID); // Filtered Array // [{ id: 15 }, { id: -1 }, { id: 3 }, { id: 12.2 }] console.log('Number of Invalid Entries = ', invalidEntries); // Number of Invalid Entries = 5
参考:
The text was updated successfully, but these errors were encountered:
No branches or pull requests
filter
参数
callback
用来测试数组的每个元素的函数。返回 true 表示该元素通过测试,保留该元素,false 则不保留。它接受以下三个参数
数组中当前正在处理的元素
正在处理的元素在数组中的索引
调用了 filter 的数组本身
thisArg(可选)
执行 callback 时,用于 this 的值
返回值:一个新的、由通过测试的元素组成的数组,如果没有任何数组元素通过测试,则返回空数组。
模拟实现
参考:
The text was updated successfully, but these errors were encountered: