This article will write arrays in common ways

ForEach, map, filter, some, every, reduce…. As you can see, these methods are basically just passing in a function, processing the data, processing it, and returning the result that we want.

map

map:

Empty arrays are not detected

Returns a new array

  • grammar
array.map(function(currentValue,index,arr), thisValue)
Copy the code
Array.prototype._map = function (fn, thisArr) {
      if (this= =undefined) {
        throw new TypeError('this is null or not undefined');
    }
     if (Object.prototype.toString.call(fn) ! = ='[object Function]') {
        throw new TypeError(fn + 'is not a function');
    }
    let res = [] 
    let mapArr = this / / [1, 2, 3]
    for (let i = 0; i < mapArr.length; i++) {
        res[i] = fn.call(thisArr, mapArr[i], i, mapArr)
    }
    return res
}
let arr = [1.2.3]
let mapRes = arr._map((val, index, item) = > {
    return val + 1
})
console.log(mapRes)/ / / 2 and 4

Copy the code

These so-called methods, is the internal package good, easy to use. Like a handwritten map,

  • Because we’re going to return a new array, we’re going to declare an empty array, and then we’re going to return, and what we’re going to do is we’re going to call fn every time and assign to fn. Assign to the new array returned. By the time you use a map, you’ll see the logic in action, eg:val+1. How do you internally get val,index, and item, and how do each of those correspond to each other, you don’t care

forEach

The forEach:

An empty array does not execute a callback.

Change the original array

The return value is undefined

  • grammar
array.forEach(function(currentValue, index, arr), thisValue)
Copy the code
  • For details, see map, which returns a new array, and forEach, which changes the original array.

filter

filter:

Empty arrays are not checked

Returns a new array

  • grammar
array.filter(function(currentValue, index, arr), thisValue)
Copy the code
Array.prototype._filter = function (fn, thisArr) {
       if (this= =undefined) {
        throw new TypeError('this is null or not undefined');
    }
     if (Object.prototype.toString.call(fn) ! = ='[object Function]') {
        throw new TypeError(fn + 'is not a function');
    }
    let filterArr = this
    let filterRes = []
    for (let i = 0; i < filterArr.length; i++) {
        if (fn.call(thisArr, filterArr[i], i, filterArr)) {
            filterRes.push(filterArr[i])
        }

    }
    return filterRes
}
let arr = [1.2.3]
let filRes = arr._filter((val, index, item) = > {
    return val > 1
})
console.log(filRes)/ / [2, 3]
Copy the code
  • The filter method is used to filter data. When the condition is satisfied, the value that satisfies the condition is returned

  • If (fn. Call (thisArr, filterArr[I], I, filterArr) {}

  • Filterres.push (filterArr[I])

some

some:

Empty arrays are not checked

Returns a new array

  • grammar
array.some(function(currentValue, index, arr), thisValue)
Copy the code
Array.prototype._some = function (fn, thisArr) {
      if (this= =undefined) {
        throw new TypeError('this is null or not undefined');
    }
     if (Object.prototype.toString.call(fn) ! = ='[object Function]') {
        throw new TypeError(fn + 'is not a function');
    }
    let someArr = this
    for (let i = 0; i < someArr.length; i++) {
        if (fn.call(thisArr, someArr[i], i, someArr)) {
            return true}}return false
}
let arr = [1.2.3]
let someRes = arr._some((val, index, item) = > {
    return val > 1
})
console.log(someRes)// true
Copy the code
  • Some also filters data, except that it returns true/false. If you haveaElement meets the condition, returnstrue , The remaining elements will not be tested.

every

  • Every also filters data. Except he returns true/false. ifAll the elements satisfy the condition, the returntrueReturns any element that does not meet the conditionfalse
Array.prototype._every = function (fn, thisArr) {
       if (this= =undefined) {
        throw new TypeError('this is null or not undefined');
    }
     if (Object.prototype.toString.call(fn) ! = ='[object Function]') {
        throw new TypeError(fn + 'is not a function');
    }
    let everyArr = this
    for (let i = 0; i < everyArr.length; i++) {
        if(! fn.call(thisArr, everyArr[i], i, everyArr)) {return false}}return true

}
let arr = [1.2.3]
let everyRes = arr._every((val, index, item) = > {
    return val > 0
})
console.log(everyRes)// true
Copy the code
  • The implementation of every and some, I think, is interesting

  • Every returns true if all conditions are met. So judge first

  • if (! fn.call(thisArr, everyArr[i], i, everyArr)) { return false }

  • Some returns true as long as one condition is satisfied

  • if (fn.call(thisArr, everyArr[i], i, everyArr)) { return true }

  • You product, you fine product 😁

reduce

  • The Reduce method accepts a function as an accumulator, and each value in the array (from left to right) is reduced to a value.
  • grammar
array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
Copy the code
Array.prototype._reduce = function (fn, init) {
      if (this= =undefined) {
        throw new TypeError('this is null or not undefined');
    }
     if (Object.prototype.toString.call(fn) ! = ='[object Function]') {
        throw new TypeError(fn + 'is not a function');
    }
    let reduceArr = this
    let index = arguments.length === 1 ? 1 : 0 // get the index. If no initial value is passed, then index is 1, because no initial value is passed, prev is the initial value, and the subscript is 0, so naturally curr is 1
    let prev = arguments.length === 1 ? reduceArr[0] : init // Get the initial value. If no initial value is passed in, the initial value is the first item in the array, otherwise the initial value init is passed in
    for (let i = index; i < reduceArr.length; i++) {
        prev = fn(prev, reduceArr[i], i, reduceArr)  // iteration accumulation
    }
    return prev
}
let arr = [1.2.3]
let reduceRes = arr._reduce((prev, curr) = > {
    return prev + curr
})
console.log('reduceRes', reduceRes)/ / 6
let reduceResParams = arr._reduce((prev, curr) = > {
    return prev + curr
}, 2)
console.log('reduceResParams', reduceResParams)/ / 8
Copy the code
  • Argument. length === 1 indicates that no argument is passed in
  • The index of reduce is a point of concern because ifPassing in initial value, then the current valuecurrFrom the firstaStudent: Yes, soThe index is 0If theNo initial value is passed in, thencurrFrom the firsttwoI’m starting to count, soThe index is 1
  • Initial PreV value of Reduce. ifPassing in initial value, so the initial value isinit, no initial value is passed, which is the first element of the arrayreduceArr[0]
  • Reduce, as an accumulator, can be thought of asa = a+ 1The simple logic of
prev = fn(prev, reduceArr[i], i, reduceArr)  // iteration accumulation
Copy the code

includes

  • The string () method is used to determine whether the string contains the specified substring.

  • Returns true if a matching string is found, false otherwise.

  • grammar

String.includes(searchvalue, start)
Array.includes(searchvalue, start)
Copy the code
Array.prototype._includes = function (searchElement, formIndex = 0) {
    let includesEle = this
    let len = includesEle.length
    if(searchElement.length >= len || ! len)return false // If the start bit is greater than the length of the data, or there is no data
    for (let i = formIndex; i < len; i++) {
        if (includesEle[i] === searchElement) // Return true when the incoming data matches the sought data
            return true
    }
    return false
}
let arr = [1.2.3]
let includes = arr._includes(1)
console.log('includes', includes)// true
Copy the code
  • So here we knowlenIf (this == undefined) {throw new TypeError(‘this is null or not undefined’); } isA truth

indexOf

  • IndexOf (item, start) start specifies the position to start the search. If no index is found, -1 is returned

  • Its implementation is exactly the same as includes. Includes returns true/ false. In indexOf, true returns array subscripts and false returns -1

rray.prototype._indexOf = function (searchElement, formIndex = 0) {
    let indexOf = this
    let len = indexOf.length
    if(searchElement.length >= len || ! len)return -1 // If the start bit is greater than the length of the data, or there is no data
    for (let i = formIndex; i < len; i++) {
        if (indexOf[i] === searchElement) // Return true when the incoming data matches the sought data
            return i
    }
    return -1
}
let arr = [1.2.3]
let _indexOf = arr._indexOf(3)
let _indexOf2 = arr._indexOf(33)
console.log('_indexOf', _indexOf)/ / 2
console.log('_indexOf2', _indexOf2)// -1


Copy the code

conclusion

  • In all methods, you pass in a function, so the first thing to do is determine whether it’s a function

    Object.prototype.toString.call(fn) ! = ='[object Function]'
    
    typeoffn ! = ='function'
    Copy the code
  • Call (thisArr, filterArr[I], I, filterArr) fn(filterArr[I], I, filterArr) fn(thisArr, filterArr[I], I, filterArr) I’m here to pander to his usage 😂

ThisValue: Optional. The value passed to the function is usually the “this” value. If this parameter is empty, “undefined” is passed to the value “this”

  • What we remember about this is that it points to whoever calls it, and when it points to it, in fact,This also represents the data to point to. Let filterArr = this is a good oneGet caller dataThe way of
  • You’re returning new data, so declare an empty array and return it
  • The above handwriting, found many similarities
Array.prototype._every = function (fn, thisArr) {
    if (this= =undefined) {
        throw new TypeError('this is null or not undefined');
    }
     if (Object.prototype.toString.call(fn) ! = ='[object Function]') {
        throw new TypeError(fn + 'is not a function');
    }
    let everyArr = this
    for (let i = 0; i < everyArr.length; i++) {
        
    }
}
Copy the code