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

    11,Array的indexOf方法

    indexOf()方法返回在数组中可以找到一个给定元素的第一个索引,如果不存在,则返回-1。
    语法:arr.indexOf(searchElement[, fromIndex = 0])
    注意:1,返回找到的索引或者不存在的-1。2,不改变原数组

    Array.prototype._indexOf = function(){
     	if(this === null){throw new TypeError('"this" is null or not defined');}
     	
     	let that = Object(this),len = that.length >>> 0,param = arguments;
     	
     	if(param[1] && Math.abs(param[1])>= len)return -1;
     	
     	startIndex = Math.max((param[1] ? param[1] : 0), 0) ;
     	
     	while(startIndex < len){
     		if(startIndex in that && param[0] === that[startIndex])return startIndex;
     		startIndex++;
     	}
     	return -1;
     }

    测试1:只有一个参数

    let a = [2, 9, 7, 8, 9]; 
     console.log(a._indexOf(2)); // 0 
     console.log(a._indexOf(6)); // -1
     console.log(a._indexOf(7)); // 2
     console.log(a._indexOf(8)); // 3
     console.log(a._indexOf(9)); // 1


    测试2:两个参数

    let array = [2, 5, 9];
     console.log(array._indexOf(2, -1)); // -1
     console.log(array._indexOf(2, -3));// 0

    测试3:找出指定元素出现的所有位置

    var indices = [];
    var array = ['a', 'b', 'a', 'c', 'a', 'd'];
    var element = 'a';
    var idx = array._indexOf(element);
    while (idx != -1) {
      indices.push(idx);
      idx = array._indexOf(element, idx + 1);
    }
    console.log(indices);
    // [0, 2, 4]

    其他

    [我的博客,欢迎交流!](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)

  • 相关阅读:
    Leetcode167-Two Sum II Input array is sorted-Easy
    Leetcode122-Best Time to Buy and Sell Stock II-Easy
    Leetcode121-Best Time to Buy and Sell Stock I
    Leetcode118_Pascal's Triangle_Easy
    Leetcode88_Merge Sorted Array_Easy
    Leetcode66-Plus One-Eassy
    Open DS
    python, general, for quick review
    [python] CSV read and write using module xlrd and xlwt
    [python] xlrd
  • 原文地址:https://www.cnblogs.com/linewman/p/9918547.html
Copyright © 2011-2022 走看看