Skip to content
New issue

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方法模拟实现 #39

Open
conan1992 opened this issue Jun 28, 2020 · 0 comments
Open

数组filter方法模拟实现 #39

conan1992 opened this issue Jun 28, 2020 · 0 comments

Comments

@conan1992
Copy link
Owner

filter

filter() 方法创建一个新数组, 其包含通过所提供函数实现的测试的所有元素。

参数

var newArray = arr.filter(callback(element[, index[, array]])[, thisArg])

  • callback
    用来测试数组的每个元素的函数。返回 true 表示该元素通过测试,保留该元素,false 则不保留。它接受以下三个参数

    • element
      数组中当前正在处理的元素
    • index(可选)
      正在处理的元素在数组中的索引
    • array(可选)
      调用了 filter 的数组本身
  • 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

参考:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant