This article has participated in the Denver Nuggets Creators Camp 3 “More Productive writing” track, see details: Digg project | creators Camp 3 ongoing, “write” personal impact

preface

I’ve encapsulated the core methods of ES3 arrays before, but there are new versions of ES5 and ES6. A release and a new iteration inevitably removes some of the old stuff and adds some useful stuff. This time let’s take a look at the new array method in ES5 and implement encapsulation

The new method

First, we categorize these methods:

  • Two index methods: indexOf() and lastIndexOf()
  • 5 iterative methods: forEach(), map(), filter(), some(), every()
  • Two merging methods: Reduce () and reduceRight()

Let’s look at a simulated implementation of the first two methods

IndexOf () and lastIndexOf ()

Both methods are used to return the index position of the element in the array when it was first found, or -1 if not. Both receive two arguments:

  1. The first argument is what to look for
  2. The second argument is the index to find the starting position, which defaults to 0 if the default or formatting is incorrect. The second parameter is optional

The difference is that one looks from front to back, and one looks from back to front

The basic use

Let’s look at an example. Let’s define an array:

var arr = [1.2.3.4.5.6];
Copy the code

IndexOf () : Searches backwards from the beginning of the array.

console.log(arr.indexOf(3));//2 passes only one value, starting with the 0th item by default until the index is returned
console.log(arr.indexOf(10));// If -1 is not found, return -1
console.log(arr.indexOf());//-1 does not pass anything, returns -1
console.log(arr.indexOf(3.'a'));//2 pass two values, the second format is not correct, default to start the search from 0
console.log(arr.indexOf(3.2));//2 starts at item 2 and returns the location found
Copy the code

LastIndexOf () : Searches forward from the end of the array.

console.log(arr.lastIndexOf(3));//2 value passes a value indicating that the search starts from the last digit, and the return index is found
console.log(arr.lastIndexOf(7));// If -1 is not found, return -1
console.log(arr.lastIndexOf());//-1 does not pass anything, returns -1
console.log(arr.lastIndexOf(3.'a'));/ / 1
console.log(arr.lastIndexOf(1.'a'));//0 passes two values, the second format is not correct, the default is to start from the last digit, that is, to find only one digit
console.log(arr.lastIndexOf(3.2));// The second digit of 2 is a normal value. Start at that position and return -1 if not found
Copy the code

One small difference is that when the second argument fails, indexOf() defaults to bit 0, resulting in indexOf() searching the entire array, while lastIndexOf searches only the 0th bit.

When looking for comparisons, the congruence operator “===” is used, requiring exact equality or returning -1.

console.log(arr.indexOf('1'))// "1" is not equal to "1"
Copy the code

There is also no implicit type conversion for the second parameter

console.log(arr.lastIndexOf(3.'1'));/ / 1
Copy the code

Simulate encapsulation _indexOf

Array.prototype._indexOf = function (val, start) {
  var self = this;
  if (arguments.length == 0) {
    return -1;
  }
  if (arguments.length == 1) {
    return _searchFromZero();
  }
  if (arguments.length >= 2) {
    // We have to deal with the second argument: the case that accepts negative values and the case that accepts error values.
    if (typeofstart ! = ="number" || isNaN(start)) {
      return _searchFromZero();
    }
    // Numbers can be positive or negative. Negative numbers can be converted into positive numbers by operation
    if (typeof start === "number"&&!isNaN(start)) {
      start = start >= 0 ? start : start + this.length;
      var temp = 0;
      for (var i = start; i < this.length; i++) {
        temp++;
        if (this[i] === val) {
          return start + temp - 1;// become the subscript}}return -1; }}function _searchFromZero() {
    for (var i = 0; i < self.length; i++) {
      if (self[i] === val) {
        returni; }}return -1; }}Copy the code

test

// test code
console.log(arr._indexOf(3));//2 passes only one value, starting at 0 by default
console.log(arr._indexOf(7));// If -1 is not found, return -1
console.log(arr._indexOf());//-1 does not pass anything, returns -1
console.log(arr._indexOf(3.'a'));//2 The second format is not correct
console.log(arr._indexOf(3.0));/ / 2
console.log(arr._indexOf(3, -4));/ / 2
console.log(arr._indexOf(3, -5));/ / 2
console.log(arr._indexOf(3.100));/ / 1
Copy the code

The simulation implements the basic use of indexOf!

Mock wrapper _lastIndexOf

Array.prototype._lastIndexOf = function (val, start) {
  var self = this;
  if (arguments.length == 0) {
    return -1;
  }

  if (arguments.length == 1) {
    return _searchFromEnd();
  }
  function _searchFromEnd() {
    for (var i = self.length - 1; i > 0; i--) {
      if (self[i] === val) {
        returni; }}return -1;
  }
  if (arguments.length >= 2) {
    // Pass two values, the second format is not correct, the default is to start the search from the last digit (0), just look for one digit. The first bit returns 0, not -1
    if (typeofstart ! = ="number" || isNaN(start)) {
      return self[0] === val ? 0 : -1;
    }
    // Otherwise, it is the number. There should also be positive and negative numbers, so we have to rotate.
    if (typeof start === "number"&&!isNaN(start)) {
      // The positive digit is the start digit
      start = -start + self.length;
      // It can be a negative number or a positive number.
      start = start >= 0 ? start : start + self.length;
      // console.log(start)
          // var temp = 0;
          for (var i = start; i > 0; i--) {
            // temp++;
            if (self[i] === val) {
              return i;// become the subscript}}return -1; }}}Copy the code

test

console.log(arr._lastIndexOf());//-1 does not pass anything, returns -1
console.log(arr._lastIndexOf(3));//2 value passes a value indicating that the search starts from the last digit
console.log(arr._lastIndexOf(3.'a'));/ / 1
 console.log(arr._lastIndexOf(1.'a'));// the last digit of the array is the last digit of the array.
console.log(arr._lastIndexOf(3.2));// The second digit of 2 is a normal value
Copy the code

The simulation implements the basic use of lastIndexOf!

END

That’s all for this article

If you have any questions, please leave a comment