Array

MDN definition: JavaScript Array objects are global objects used to construct arrays, which are high-order objects similar to lists.

Several ways to create arrays

Let a = new Array('apple', 'bear', 'bear'); 'banana')// Constructor assignment gives the contents of the array directlyCopy the code

Array common API

The methods of manipulating arrays are divided into pure function methods and non-pure function methods. Pure function methods do not change the original array, and non-pure function methods conversely, the apis described below are some common apis ((other implementations please comment below, or you write your own).

/* Pure function API: concat filter Map reduce slice non-pure function API splice shift(same as unshift) reverse */
Copy the code

Pure functions API

Array.prototype.concat

MDN definition: The concat() method is used to merge two or more arrays. This method does not change an existing array, but returns a new array.

grammar

var new_array = old_array.concat(value1[, value2[, ...[, valueN]]])
let arr = ['name' , {a:'zhoujing'}]
let b = [].concat(arr)
//b = ['name' , {a:'zhoujing'}]
arr[1].a = 'lvshui'
//b =['name',{a:'lvshui'}] 
Copy the code

Points to be aware of

  • The concat method does not alter this or any of the arrays provided as arguments, but returns a shallow copy. That is, if there is a reference object in the array, the reference address is copied

Implement a simple concat

// Implement a simple concat
Array.prototype._concat = function(. args){
    let context = this , result = [];
    if(! args.length){return context
    }
    // If there are no arguments, just return this
    args.forEach( item= > {
      if(Object.prototype.toString.call(item) ! = ='[object Array]'){
        result.push(item)
        // Check if there is an array in the argument
      }else{
        item.forEach( it= > result.push(it))
      }
    })
    return result
}
console.log( []._concat(1.2.3.3.45))
console.log( []._concat(1.2.3, {name:'dd'},45))
console.log( []._concat([1[2]],3.3.45))
console.log( []._concat() )
// [1, 2, 3, 3, 45]
// [ 1, 2, 3, { name: 'dd' }, 45 ]
// [1, [2], 3, 3, 45]
/ / []
Copy the code

Array.prototype.filter

MDN definition: The filter() method creates a new array containing all the elements of the test implemented by the provided function.

grammar

var new_array = arr.filter(callback(element[, index[, array]])[, thisArg])
Copy the code

Points to be aware of

  • The filter method does not alter the original array; it returns the filtered new array.
  • This process is one-time, and subsequent array changes do not affect the value of filter

Implement a simple filter function

// Implement a simple filter
Array.prototype._filter = function(cb,thisArg){
    let context = this
    let cbThis = thisArg ? thisArg : null
    let result = []
    // This points to this by default, providing thisArg in case pointing to thisArgs
    context.forEach( (item,index,arr) = > {
      if(cb.call(cbThis,item,index,arr)){
        result.push(item)
      }
    })
    return result
}
console.log( [1.2.3.43]._filter( item= > item&1= =1))console.log( []._filter(item= > item&1= =1[1.2.3.43]))//[1, 3, 43]
/ / []
Copy the code

Array.prototype.map

MDN definition: The map() method creates a new array with the result that each element in the array is the return value of a call to the provided function.

grammar

var new_array = arr.map(function callback(currentValue[, index[, array]]) {
 // Return element for new_array 
}[, thisArg])
Copy the code

Points to be aware of

  • The map method does not change the original array; it returns a new array.
  • The callback function is automatically passed three parameters: the array element, the element index, and the original array itself.
  • The second argument to the map function is optional, referred to as this for the callback
// Implement a simple map
Array.prototype._map = function(cb,thisArg){
    let context = this
    let cbThis = thisArg ? thisArg : null
    let result = []
    // This points to this by default, providing thisArg in case pointing to thisArgs
    context.forEach( (item,index,arr) = > {
       result.push( cb.call(cbThis,item,index,arr) )
      }) 
      return result
    }
console.log( [1.2.3]._map(Math.sqrt) )
console.log( [1.2.3]._map((index,item) = >{ return index * 2 + item}) )
// [1, 1.4142135623730951, 1.7320508075688772]
// [2, 5, 8]
Copy the code

Array.prototype.reduce

MDN definition: The reduce() method performs a reducer function (in ascending order) that you provide on each element in the array, summarizing its results into a single return value.

grammar

arr.reduce(callback(accumulator, currentValue[, index[, array]])[, initialValue])
Copy the code

Points to be aware of

  • The reduce method does not change the array; it returns a value.
  • It is safer to provide an initialValue (recommended)
// Implement a simple reduce
Array.prototype._reduce = function(reducer,initialValue){
    let context = this , startIndex = 1
    debugger
    // This points to this by default, providing thisArg in case pointing to thisArgs
    if(initialValue ! = =undefined){
        startIndex = 0
    }else{
        initialValue = context[0]}for(let i = startIndex ; i < context.length ; i ++){
        initialValue = reducer(initialValue,context[i],i,context)
    }
      return initialValue
    }
console.log([1.2.3.34]._reduce((a,b) = > a+b , 12))
console.log([1.2.3.34]._reduce((a,b) = > a.concat(b) , []))
/ / 52
// [1, 2, 3, 34]
Copy the code

Array.prototype.slice

MDN definition: The slice() method returns a new array object that is a shallow copy (including begin, but not end) of the array determined by begin and end. The original array will not be changed.

grammar

arr.slice([begin[, end]])
Copy the code

Points to be aware of

  • The slice method is a shallow copy of an array item
  • The Slice method does not modify the original array
// Implement a simple slice
Array.prototype._slice = function(. args){
    let len = this.length , result = []
    let startIndex = args[0= = =undefined ? 0 : args[0]
    let endIndex = args[1= = =undefined ? len : args[1] >= len? len:args[1]
    for(let i = startIndex ; i < endIndex ; i ++ ){
        result.push(this[i])
    }
    return result
}
console.log( [1.2.3.34.3.3.3.33.3]._slice() )
//[1, 2, 3, 34, 3,3, 33, 3]
Copy the code

Impure function API

Array.prototype.splice

MDN definition: The splice() method modifies an array by deleting or replacing existing elements or adding new ones in place, and returns the modified contents as an array. This method changes the original array.

grammar

array.splice(start[, deleteCount[, item1[, item2[, ...]]]])
Copy the code

Points to be aware of

  • Specifies the starting position of the modification (counting from 0). If the length of the array is exceeded, the contents are appended from the end of the array. If it is negative, it represents the number of bits from the end of the array (counting from -1, which means -n is the NTH element to the last and equivalent to array.length-n); If the absolute value of a negative number is greater than the length of the array, the starting position is bit 0.
  • If deleteCount is greater than the total number of elements after start, all elements after start are deleted (including the start bit). If deleteCount is omitted, or its value is greater than or equal to array.length-start (that is, if it is greater than or equal to the number of all elements after start), then all elements in the array after start are deleted. If deleteCount is 0 or negative, the element is not removed. In this case, at least one new element should be added
// Implement a simple splice
Array.prototype._splice = function(startIndex,count,... items){
    debugger
    let context = this , len = context.length;
    let temp = this.slice()
    startIndex = startIndex < 0 ? Math.abs(startIndex>=len)?0:len + startIndex : startIndex
    StartIndex = startIndex
    // This is the count value case
    count = count <=0 ? 0 : count//count can be negative
    if( count >= len - startIndex ){
        for(let i = 0 ; i < len - startIndex ; i ++){
            context.pop()
        }
        items.forEach( item= > {
            context.push(item)
        })
    }else{// In normal case
        context.length = len - count + items.length// Array in place operation
        for(let j = context.length - 1 ; j >= startIndex + count ; j--){
            context[j] = context[ j + count - items.length ]
        }
        for(let i = 0 ; i < items.length ; i ++){
            context[startIndex + i] = items[i]
        }
    }
    console.log(this)
    return count === undefined ? temp.slice(startIndex) : temp.slice(startIndex,startIndex + count)
}
console.log( [1.2.3.34]._splice(1.2.3.4.45))// [1, 3, 4, 45, 34]
// [2, 3]
Copy the code

Array.prototype.shift

MDN definition: Shift () removes the first element from the array and returns the value of that element. This method changes the length of the array.

grammar

arr.shift()
Copy the code

Points to be aware of

  • The Shift method is not limited to arrays; it can be applied to array-like objects through call or apply. The premise is that the object has a length attribute
// Implement a simple shift
Array.prototype._shift = function(){
    if(!this.length) return undefined;
    let context = this.slice()
    for(let i = 0 ; i < this.length ; i ++){
        this[i] = this[i+1]}this.length--
    console.log(this)
    return context[0]}console.log( []._shift() )
// undefined
// [ 2, undefined, 3, 4, 54, 56, 76 ]
Copy the code

Array.prototype.reverse

MDN definition: Method reverses the position of the elements in an array and returns the array. The first element of the array becomes the last, and the last element of the array becomes the first. This method changes the original array.

grammar

arr.reverse()
Copy the code

Points to be aware of

  • The transpose () method reverses the position of the elements in an array, alters the array, and returns a reference to the array.
  • Can also be applied to array-like objects.
// Implement a simple reverse
Array.prototype._reverse = function(){
    if(!this.length || this.length === 1) return this;
    let len = this.length , middle = parseInt(len / 2)
    for(let i = 0 ; i < middle ; i++){
        index = this[i]
        this[i] = this[len-i-1]
        this[len-i-1] = index
    }
    return this
}
console.log( [1.2.3.4.54.56.76]._reverse() )
console.log( [0.1.2.3.4.54.56.76]._reverse() )
// [76, 56, 54, 4,3, 2, 1]
// [76, 56, 54, 4,3, 2, 1, 0]
Copy the code