zoukankan      html  css  js  c++  java
  • 实现一个Javascript的mySplice

    闲来无事,实现一个Javascript的数组删除或替换指定范围的方法(有原生splice可用)

    思路

    1. 把截取范围后的元素向前移动,
    2. 然后删除长度范围之外的元素
    Array.prototype.mySplice = function(start, end, newItem){
      if(start > this.length || (end-start) < 0) return false;
      if(end > this.length) { 
        end = this.length - 1; 
      }
      var i = 0, 
          length = this.length, 
          endTmp = end;
      for(; i< length; i++){
        if(i >= start && endTmp < length){
          if(newItem && i === start){
            this[i] = newItem;
            continue;
          }
          this[i] = this[endTmp++];
        }
      }
      if(!newItem || end - start !== 1){
        this.length -= end - start;
      }
    };
    

    用法如下:

    //替换指定元素
    var arr1 = [1,2,3,4,5,6,6];
    arr1.mySplice(1, 2, 100);
    console.log(arr1); //[1, 100, 3, 4, 5, 6, 6]
    //替换指定范围的元素
    var arr2 = [1,2,3,4,5,6,6];
    arr2.mySplice(1, 5, 100);
    console.log(arr2);//[1, 100, 6]
    //删除指定范围的元素
    var arr3 = [1,2,3,4,5,6,6];
    arr3.mySplice(1, 5);
    console.log(arr3);//[1, 6, 6]
    
  • 相关阅读:
    【bzoj1010】[HNOI2008]玩具装箱toy
    bzoj 3173
    bzoj 1179
    bzoj 2427
    bzoj 1051
    bzoj 1877
    bzoj 1066
    bzoj 2127
    bzoj 1412
    bzoj 3438
  • 原文地址:https://www.cnblogs.com/dotcoder/p/5162544.html
Copyright © 2011-2022 走看看