zoukankan      html  css  js  c++  java
  • Array对象的方法实现(3)----Array.prototype.filter和Array.prototype.find(实现常规参数的功能)

    6,Array的filter方法

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

    //注意:1,返回一个新的数组。2,不改变原数组

    //语法:arr.filter(callback[, thisArg]);

    Array.prototype._filter = function(fn){
    	if(this === null) throw new TypeError('this is null or not defined'); 
    	
    	let that = Object(this);
    	
    	if(typeof fn !== 'function') throw new TypeError('fn is not function');
    	
    	let new_arr = [];
    	
    	for(let i = 0;i < that.length>>>0;i++){
    		fn(that[i]) && new_arr.push(that[i]);
    	}
    	
    	return new_arr;
    }

    https://developer.mozilla.org:

    Array.prototype.filter = function(fun /* , thisArg*/)
      {
        "use strict";
    
        if (this === void 0 || this === null)
          throw new TypeError();
    
        var t = Object(this);
        var len = t.length >>> 0;
        if (typeof fun !== "function")
          throw new TypeError();
    
        var res = [];
        var thisArg = arguments.length >= 2 ? arguments[1] : void 0;
        for (var i = 0; i < len; i++)
        {
          if (i in t)
          {
            var val = t[i];
    
            // NOTE: Technically this should Object.defineProperty at
            //       the next index, as push can be affected by
            //       properties on Object.prototype and Array.prototype.
            //       But that method's new, and collisions should be
            //       rare, so use the more-compatible alternative.
            if (fun.call(thisArg, val, i, t))
              res.push(val);
          }
        }
    
        return res;
    };

    测试:

    function isBigEnough(value) {
      return value >= 10;
    }
    
    console.log([12, 5, 8, 130, 44].filter(isBigEnough));//[12,130,44]
    console.log([12, 5, 8, 130, 44]._filter(isBigEnough));//[12,130,44]

    根据mozilla社区阅读的代码,在我实现filter的时候添加对this和fn的判断,使代码更不容易出错。

    7,Array的find方法
    //find() 方法返回数组中满足提供的测试函数的第一个元素的值。否则返回 undefined。
    //注意:1,返回第一个满足要求的值,否则返回undefined。2,不改变原数组
    //语法:arr.find(callback[, thisArg]);

    Array.prototype._find = function(fn){
    	if(this === null) throw new TypeError('this is null or not defined'); 
    	
    	let that = Object(this),len = that.length>>>0;
    	
    	if(typeof fn !== 'function') throw new TypeError('fn is not function');
    	
    	for(let i = 0;i < len;i++){
    		 if(fn(that[i]))return that[i] ;
    	}
    	return undefined;
    }

    测试1:返回数组中第一个大于15的值

    function isBigEnough(element) {
      return element >= 15;
    }
    
    console.log([12, 5, 8, 130, 44].find(isBigEnough));//130
    console.log([12, 5, 8, 130, 44]._find(isBigEnough));//130

    测试2:返回数组中第一个质数

    function isPrime(element, index, array) {
      var start = 2;
      while (start <= Math.sqrt(element)) {
        if (element % start++ < 1) {
          return false;
        }
      }
      return element > 1;
    }
    
    console.log([4, 6, 8, 12].find(isPrime)); // undefined
    console.log([4, 5, 8, 12].find(isPrime)); // 5
    
    console.log([4, 6, 8, 12]._find(isPrime)); // undefined
    console.log([4, 5, 8, 12]._find(isPrime)); // 5

    测试3:返回数组中name为cherries的对象

    var inventory = [
        {name: 'apples', quantity: 2},
        {name: 'bananas', quantity: 0},
        {name: 'cherries', quantity: 5}
    ];
    
    function findCherries(fruit) { 
        return fruit.name === 'cherries';
    }
    
    console.log(inventory.find(findCherries)); // { name: 'cherries', quantity: 5 }
    
    console.log(inventory._find(findCherries)); // { name: 'cherries', quantity: 5 }

    注意:

    (1,undefined必须在遍历完没找到的情况下返回,因此是在循环外返回undefined

    这两个方法通过测试,基本没有问题,目前没有回传thisArg参数处理
    相关链接:

    filter:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
    find:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/find

    其他

    [我的博客,欢迎交流!](http://rattenking.gitee.io/stone/index.html)

    [我的CSDN博客,欢迎交流!](https://blog.csdn.net/m0_38082783)

    [微信小程序专栏](https://blog.csdn.net/column/details/18335.html)

    [前端笔记专栏](https://blog.csdn.net/column/details/18321.html)

    [微信小程序实现部分高德地图功能的DEMO下载](http://download.csdn.net/download/m0_38082783/10244082)

    [微信小程序实现MUI的部分效果的DEMO下载](http://download.csdn.net/download/m0_38082783/10196944)

    [微信小程序实现MUI的GIT项目地址](https://github.com/Rattenking/WXTUI-DEMO)

    [微信小程序实例列表](http://blog.csdn.net/m0_38082783/article/details/78853722)

    [前端笔记列表](http://blog.csdn.net/m0_38082783/article/details/79208205)

    [游戏列表](http://blog.csdn.net/m0_38082783/article/details/79035621)

  • 相关阅读:
    Android面试题目整理与解说(二)
    大学?做码农?做project师?
    图形学领域的关键算法及源代码链接
    假设在本地搭一个server和mysql数据库环境,假设使用java来訪问数据库
    [容斥原理] hdu 4135 Co-prime
    leetcode第一刷_Merge Intervals
    关于HashMap的一些深入探索与理解
    摄像头拍照上传
    rowid快速分页解析
    flare-spork: 自己维护的Pig on Spark项目
  • 原文地址:https://www.cnblogs.com/linewman/p/9918550.html
Copyright © 2011-2022 走看看