This article is participating in the nuggets team number online activity, click to see the dachang spring recruiting positions

I. Title Description:

Implement indexOf methods in the simplest possible code

Ii. Analysis of Ideas:

Both arrays and strings have indexOf methods, which find the first indexOf a given element and return -1 if none exists

  • SearchValue: The string value to be searched.
  • FromIndex Optional: A number indicates the location to start the search. Can be any integer. The default value is 0. If fromIndex is less than 0, it is equivalent to null. If fromIndex is greater than or equal to str.length, -1 is returned.

Iii. AC Code:

    // The most concise is what kind, whoo-hoo, I cried
      function indexOf(searchValue, fromIndex = 0) {
        if (this.length < 1 || fromIndex > searchValue.length) {
          return -1;
        }
        if(! searchValue) {return 0;
        }
        fromIndex = fromIndex <= 0 ? 0 : fromIndex;
        for (let i = fromIndex; i < this.length; i++) {
          if (this[i] == searchValue) return i;
        }
        return -1;
      }
      Array.prototype.myIndexOf = indexOf;
      String.prototype.myIndexOf = indexOf;
      console.log([1.2.3].myIndexOf(2));
      console.log('123'.myIndexOf(2));
      
Copy the code

Iv. Summary:

Try to get to a Nuggets event and check in;