当前位置:网站首页>JS array + array method reconstruction

JS array + array method reconstruction

2022-07-06 11:35:00 Advanced diary

javaScript Array and array method refactoring

1. Array creation

1. Literal measure
var arr = ['1','2']
2. Function construction method
var arr = new Array('a','b')

2. Array access

​ Array variable name plus [ Indexes ]

var arr = ['1','2'];
console.log(arr[0])

3. Array API Method

  1. toString() By default, array items are returned as comma separated strings

  2. join() Use the specified string to separate array strings

    var arr = [1,5,2,8,10,{
          a:1}];
    console.log(arr);//[ 1, 5, 2, 8, 10, { a: 1 } ]
    console.log(arr.toString());//”1,5,2,8,10,[object Object]”
    console.log(arr.join(""));//”152810[object Object]”
    
  3. Array.isArray() Used to determine whether a variable is an array object

  4. Array.from() Create a new array instance from a class array object or an iteratable object

  5. Array.of() Create a new array instance based on a set of parameters , Support any number and type of parameters

    var arr = Array.from("abc");
    Array.isArray(arr)//true
    console.log(arr);
    // The output is ["a","b","c"]
    Array.of(1, 2, 3); // [1, 2, 3]
    
  6. Array.prototype.push() Add one or more elements... To the end of the array , And returns the new length

  7. Array.prototype.pop() Used to delete the last element of the array and return the deleted element

  8. Array.prototype.shift() Used to remove the first element of the array from it , And returns the value of the first element

  9. Array.prototype.unshift() Add one or more elements to the beginning of an array , And returns the new length

    // The result of function running separately 
    var arr = ['zs','ls','ww'];
    // push()  Add elements at the end 
    arr.push('123');//['zs','ls','ww','123']
    // pop()  Delete the last element , Return to delete element 
    arr.pop();//['zs','ls']
    // shift  Delete first element , Return to delete element 
    arr.shift();//['ls','ww'];
    // unshift  Add the element in the first 
    arr.unshift('23')//['23','zs','ls','ww'];
    
  10. Array.prototype.reverse() Used to reverse the order of elements in an array

    var arr = ['zs','ls','ww'];
    arr.reverse()//['ww','ls','zs']
    
  11. Array.prototype.sort() Sort array elements , Default ascending order without transferring parameters

    // Descending 
    var arr = [40,100,1,5,25,10];
    arr.sort(function(a,b){
          
    	return b-a
    });
    
  12. Array.prototype.concat() Used to connect two or more arrays

    array1.concat(array2,array3,...,arrayX)
    
  13. Array.prototype.slice() Returns the selected element from an existing array

    //slice(start,end)
    var arr = ["a", "b", "c", "d", "e"]; 
    var result = arr.slice(1,3);//b,c
    
  14. Array.prototype.splice() Used to add or delete elements in an array

    // Parameter 1 is where to start   Parameter 2 is the number of elements deleted   Parameter 3 starts with the added element 
    var arr = ["a", "b", "c", "d"];
    arr.splice(2,0,"e","f");//a,b,e,f
    
  15. Array.prototype.indexOf() Returns the position of a specified element in an array

    var arr = ["Banana", "Orange", "Apple", "Mango"]; 
    var a = arr.indexOf("Apple",0);// from 0 Start searching at the sign   return 2
    
  16. Array.prototype.lastIndexOf() Returns the last position of a specified element in the array , From the back to the front

    var arr = ["Banana", "Orange", "Apple", "Mango"]; 
    var a = arr.lastIndexOf("Apple",0);// from 0 Start searching at the sign   return 2
    
  17. Array.prototype.every() Checks whether all elements of the array meet the specified conditions

    var ages = [32, 33, 16, 40];
    var result = ages.every(function (age) {
          
      return age >= 18
    })
    console.log(result);// The output is :false
    
  18. Array.prototype.some() Check whether the elements in the array meet the specified conditions

    var ages = [32, 33, 16, 40];
    
    var result = ages.some(function (age) {
          
      return age >= 18
    })
    console.log(result);// The output is :true
    
  19. Array.prototype.filter() Create a new array , The elements in the new array are checked by checking all the eligible elements in the specified array

    var ages = [32, 33, 16, 40];
    
    var result = ages.filter(function (age) {
          
      return age >= 18
    })
    console.log(result);// The output is :[ 32, 33, 40 ]
    
  20. Array.prototype.map() Returns a new array , The element in the array is the value after the original array element calls the function

    var numbers = [4, 9, 16, 25];
    
    var result = numbers.map(function (number) {
          
      return Math.sqrt(number)
    })
    console.log(result);// The output is :[ 2, 3, 4, 5 ]
    
  21. Array.prototype.forEach() Call each element of the array , And pass the element to the callback function

    var age = [35,21,32,51];
    age.forEach(function (item,index) {
          
      console.log(item,index);
    })
    //35 0
    //21 1
    //32 2
    //51 3
    

4. Array method reconstruction

  1. push Method refactoring

    var arr = new Array();
    arr = ['123', '24', '214', 124];
    // Two way 
    // Array.prototype.myPush = function (str) {
          
    // if (str == null) {
          
    // return this.length;
    // } else {
          
    // this[this.length] = str;
    // }
    // return this.length;
    // }
    Array.prototype.myPush = function (str) {
          
      for (let i = 0; i < arguments.length; i++) {
          
        this[this.length] = arguments[i];
      }
      return this.length;
    }
    
    // arr.myPush('12');
    // console.log(arr);
    
  2. pop Method rewriting

    Array.prototype.myPop = function () {
          
     if (this.length==0) {
          
      	return undefined;
     }
     let temp = this[this.length - 1]
     this.length--;
     return temp;
    }
    // arr.myPop()
    // console.log(arr.myPop());
    
  3. shift Method rewriting

    Array.prototype.myShift = function () {
          
      let temp = this[0];
      for (let i = 0; i < this.length; i++) {
          
        this[i] = this[i + 1];
      }
      this.length = this.length - 1
      return temp;
    }
    // arr.myShift()
    // console.log(arr);
    
  4. unshift Method rewriting

    var aa = [123, 124, 125]
    Array.prototype.myUnShift = function () {
          
      var result = this.length + arguments.length;
      for (let i = result; i > 0; i--) {
          
        if (i > arguments.length) {
          
          this[i - 1] = this[i - 1 - arguments.length]
        } else {
          
          this[i - 1] = arguments[i - 1]
        }
      }
      return result;
    }
    // aa.myUnShift('13','666','wrw',123)
    // console.log(aa);
    
  5. reverse Method rewriting

    Array.prototype.myReverse = function () {
          
      var arr = [];
      for (let j = 0; j < this.length; j++) {
          
        arr[j] = this[j];
      }
      for (let i = 0; i < this.length; i++) {
          
        this[i] = arr[this.length - i - 1];
      }
      return this;
    }
    
  6. concat Method rewriting

    Array.prototype.myConcat = function (str) {
          
      let arr = [];
      for (let o = 0; o < this.length; o++) {
          
        arr[o] = this[o]
      }
      if (str == '') {
          
        return arr;
      }
      for (let x = 0; x < arguments.length; x++) {
          
        if (Array.isArray(arguments[x])) {
          
          for (let i = 0; i < arguments[x].length; i++) {
          
            arr[arr.length] = arguments[x][i]
          }
        } else if (!Array.isArray(arguments[x])) {
          
          arr[arr.length] = arguments[x]
        }
      }
      return arr;
    }
    var q = [123, 53, 1]
    var x = abc.myConcat('c', q, 'd', q)
    // console.log(x,abc);
    
  7. slice Method rewriting

    Array.prototype.mySlice = function (start, end) {
          
      let arr = [];
      if (start > end && end != '') {
          
        return this;
      } else {
          
        if (start < 0) {
          
          start = this.length + start;
        }
        if (end < 0) {
          
          end = this.length + end;
        }
        if (end == null) {
          
          console.log(123);
          for (let i = start; i < this.length; i++) {
          
            arr[i - start] = this[i];
          }
        } else {
          
          if (end > this.length) {
          
            end = this.length;
          }
          for (let j = start; j < end; j++) {
          
            arr[j - start] = this[j];
          }
        }
      }
      return arr;
    }
    // console.log(abc.mySlice(2,4));
    
  8. forEach restructure

    Array.prototype.myForEach=function(fun) {
          
      for (let i = 0; i < arr.length; i++) {
          
        fun(this[i],i,this)
      }
    }
    
  9. every Method rewriting Methods this Point to global Do not point to the call array The second parameter is modified this Point to

    Array.prototype.myEvery = function (fun,obj) {
          
      for (let i = 0; i < this.length; i++) {
          
        if(!(obj?fun.bind(obj)(this[i]):fun(this[i]))){
          
          return false;
        }
      }
      return true;
    }
    
  10. some Method refactoring

    Array.prototype.mySome = function (fun,obj) {
          
      for (let i = 0; i < this.length; i++) {
          
        if((obj?fun.bind(obj)(this[i]):fun(this[i]))){
          
          return true;
        }
      }
      return false;
    }
    
    var result = qq.mySome(function(item) {
          
      return item<0
    })
    
  11. map Method refactoring

    Array.prototype.myMap = function(fun,obj) {
          
      let arr = [];
      for (let i = 0; i < this.length; i++) {
          
        arr.push(obj?fun.bind(obj)(this[i]):fun(this[i]))
      }
      return arr;
    }
    
  12. filter Method refactoring

    Array.prototype.myFilter = function(fun,obj) {
          
      var result = [];
      for (let i = 0; i < this.length; i++) {
          
        if (obj?fun.bind(obj)(this[i]):fun(this[i])) {
          
          result.push(this[i])
        }
      }
    }
    
原网站

版权声明
本文为[Advanced diary]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/187/202207060912570011.html