Writing in the front

Here comes the second! Blunt! Blunt! Blunt!

All the built-in methods and manual implementation of the js array

Because I was asked in an interview have you used all the built-in methods of arrays? Are you aware of the parameters and usage of all built-in methods? I didn’t have all the answers, so I decided to go through all the built-in array methods from scratch and implement them myself. It’s mainly a knowledge comb, and readers can comb it all over again. The following methods will try to achieve all their own, it is difficult to Google, and then note the source. All source code at GITHUB.

indexOf()

Searches for an element in an array and returns its location.

Example 🌰

let a = [1.2.3.NaN]
a.indexOf(2) / / 1
Copy the code

implementation

Array.prototype.indexOf2 = function (el, start = 0) {
  if (start >= this.length || start < 0) return -1
  for (let i = start; i < this.length; i++) {
    if (el === this[i]) {
      return i
    }
  }
  return -1
}
Copy the code

isArray()

Determines whether the object is an array.

Example 🌰

let a = [1.2.3.NaN]
Array.isArray(a) // true
Copy the code

implementation

Array.isArray2 = function (array) {
  return Object.prototype.toString.call(arg) === '[object Array]'
}
Copy the code

join()

Put all the elements of an array into a string.

Example 🌰

let a = [1.2.3.NaN]
a.join(', ') / / '1, 2, 3, NaN'
Copy the code

implementation

Array.prototype.join2 = function (separator = ' ') {
  let res
  for (let i = 0; i < this.length; i++) {
    if(! res) { res =this[i]
    } else {
      res += separator + this[i]
    }
  }
  return res
}
Copy the code

keys()

Returns an iterable of an array containing the original array’s key.

Example 🌰

let a = [1.2.3.NaN]
let b = a.keys()
b.next() //{value: 0, done: false}
b.next() //{value: 1, done: false}
b.next() //{value: 2, done: false}
b.next() //{value: 3, done: false}
b.next() //{value: undefiend, done: true}
Copy the code

implementation

function makeIterator(array) {
  let nextIndex = 0;
  return{[Symbol.iterator]: function() {
      return nextIndex < array.length ?
        {value: array[nextIndex++], done: false}, {value: undefined.done: true}; }}; }Array.prototype.keys2 = function () {
  let res = []
  for (let i = 0; i < this.length; i++) {
    res.push(i)
  }
  return makeIterator(res).Symbol.iterator
}
Copy the code

For more information about iterators, see ECMAScript 6: Iterator and for… Of circulation

lastIndexOf()

Searches for an element in an array and returns its last occurrence.

Example 🌰

var fruits = ["Banana"."Orange"."Apple"."Mango"];
fruits.lastIndexOf("Apple"); / / 2
Copy the code

implementation

Array.prototype.lastIndexOf2 = function (el, start = 0) {
  start = Math.abs(start)
  let res = -1
  for (let i = start; i < this.length; i++) {
    if (el === this[i] && res < i) {
      res = i
    }
  }
  if (start > 0) {
    for (let i = 0; i < this.length - start; i++) {
      if (el === this[i] && res < i) {
        res = i
      }
    }
  }
  return res
}
Copy the code

map()

Process each element of an array by specifying a function that returns the processed array.

Example 🌰

var numbers = [4.9.16.25];

numbers.map(Math.sqrt); / / 5-tetrafluorobenzoic [2]
Copy the code

implementation

Array.prototype.map2 = function (fn, context = null) {
  const res = []
  if(! context) { context =this
  }
  for (let i = 0; i < context.length; i++) {
    res.push(fn(context[i], i, context))
  }
  return res
}
Copy the code

pop()

Removes the last element of the array and returns the deleted element.

Example 🌰

let a = [1.2.3]
a.pop() / / 3, a: [1, 2]
Copy the code

implementation

Array.prototype.pop2 = function () {
  const res = this[this.length - 1]
  this.length -= 1
  return res
}
Copy the code

push()

Adds one or more elements to the end of the array and returns the new length.

Example 🌰

let a = []
a.push(1.2.3.4) / / 4, a: [1, 2, 3, 4]
Copy the code

implementation

Array.prototype.push2 = function (. el) {
  for (let i = 0; i < el.length; i++) {
    this[this.length + i] = el[i]
  }
  return this.length
}
Copy the code

reduce()

Evaluates an array element as a value (left to right).

Example 🌰

let a = [1.2.3.4]
function getSum(total, num) {
    return total + num;
}
a.reduce(getSum) / / 10
Copy the code

implementation

Array.prototype.reduce2 = function (fn) {
  let res = this[0]
  for (let i = 1; i < this.length; i++) {
    res = fn(res, this[i], i, this)}return res
}
Copy the code

reduceRight()

Evaluates an array element as a value (from right to left).

Example 🌰

let a = [1.2.3.4]
function getSum(total, num) {
    return total + num;
}
a.reduceRight(getSum) / / 10
Copy the code

implementation

Array.prototype.reduceRight2 = function (fn) {
  let res = this[this.length - 1]
  for (let i = this.length - 2; i >= 0; i--) {
    res = fn(res, this[i], i, this)}return res
}
Copy the code

reverse()

Reverses the order of the elements in an array.

Example 🌰

var fruits = ["Banana"."Orange"."Apple"."Mango"];
fruits.reverse();//["Mango", "Apple", "Orange", "Banana"]
Copy the code

implementation

Array.prototype.reverse2 = function () {
  let start = 0
  let end = this.length - 1
  while (start <= Math.floor(this.length / 2)) {
    const temp = this[start]
    this[start] = this[end]
    this[end] = temp
    start++
    end--
  }
  return this
}
Copy the code

shift()

Removes and returns the first element of the array.

Example 🌰

var fruits = ["Banana"."Orange"."Apple"."Mango"];
fruits.shift() // "Banana"
Copy the code

implementation

Array.prototype.shift2 = function () {
  const res = this[0]
  for (let i = 0; i < this.length; i++) {
    if (this[i + 1]) {
      this[i] = this[i + 1]}}this.length -= 1
  return res
}

Copy the code

slice()

Selects part of an array and returns a new array.

Example 🌰

let a = [1.2.3.4.5]
a.slice(1.2) / / [2]
Copy the code

implementation

Array.prototype.slice2 = function (start, end) {
  if(! end || end >this.length) {
    end = this.length
  }
  if(! start) { start =0
  }
  let res = []
  for (let i = start; i < end; i++) {
    res.push(this[i])
  }
  return res
}
Copy the code

some()

Checks whether any element in an array meets the specified condition.

Example 🌰

let a = [1.2.3.8]
a.some(function (item) {
    return item >= 8
}) // true
Copy the code

implementation

Array.prototype.some2 = function (fn, context) {
  if(! context) { context =this
  }
  for (let i = 0; i < context.length; i++) {
    const res = fn(context[i], i, context)
    if (res === true) {
      return res
    }
  }
  return false
}

Copy the code

sort()

Sort the elements of an array.

Example 🌰

var points = [40.100.1.5.25.10];
points.sort(function(a,b){return b-a}); / /,40,25,10,5,1 [100]
Copy the code

implementation

Array.prototype.sort2 = function (fn) {
  const res = quickSort([...this], fn)
  for (let i = 0; i < res.length; i++) {
    this[i] = res[i]
  }
  return res
}

const quickSort = function(arr, fn) {
  if (arr.length <= 1) { return arr; }
  const pivotIndex = Math.floor(arr.length / 2);
  const pivot = arr.splice(pivotIndex, 1) [0];
  const left = [];
  const right = [];
  for (let i = 0; i < arr.length; i++){
    if (fn(arr[i], pivot) < 0) {
      left.push(arr[i]);
    } else{ right.push(arr[i]); }}return quickSort(left, fn).concat([pivot], quickSort(right, fn));
};
Copy the code

splice()

Adding or removing elements from an array, returning the deleted elements, changes the array.

Example 🌰

let a = [1.2.6.4.5]
a.splice(2.1.3) / / [6] a: [6]
Copy the code

implementation

Array.prototype.splice2 = function (targetIndex, num, ... el) {
  let k = num
  const res = []
  if (el.length <= 0) {
    for (let i = targetIndex; i < this.length; i++) {
      if (this[i + num]) {
        res.push(this[i])
        this[i] = this[i + num]
      }
    }
    this.length -= num
  } else {
    let temp = []
    for (let i = targetIndex; i < this.length; i++) {
      if (res.length < num) {
        res.push(this[i])
      } else {
        temp.push(this[i])
      }
    }
    this.length = this.length - (temp.length + num)
    let len = this.length + el.length
    let j = 0
    for (let i = targetIndex; i < len; i++) {
      this[i] = el[j]
      j++
    }
    j = 0
    len = this.length + temp.length
    for (let i = this.length; i < len; i++) {
      this[i] = temp[j]
      j++
    }
  }
  return res
}
Copy the code

toString()

Converts an array to a string and returns the result (recursively).

Example 🌰

let a = [
    [1, {a:1}],
    [2.3]
]
a.toString() / / "1, [object object], 2, 3"
Copy the code

implementation

Array.prototype.toString2 = function () {
  return toStrng(this)}function toStrng (arr) {
  if (Array.isArray(arr)) {
    let res
    for (let i = 0; i < arr.length; i++) {
      if(! res) { res = toStrng(arr[i]) }else {
        res += ', ' + toStrng(arr[i])
      }
    }
    return res
  } else if (typeof arr === 'number' || typeof arr === 'string') {
    return arr
  } else {
    return Object.prototype.toString.call(arr)
  }
}
Copy the code

unshift()

Adds one or more elements to the beginning of the array and returns the new length.

Example 🌰

let a = [3.4.5]
a.unshift(1.2) / / 5 a: [1, 2, 3, 4, 5]
Copy the code

implementation

Array.prototype.unshift2 = function (. arr) {
  const temp = []
  for (let i = 0; i < this.length; i++) {
    temp.push(this[i])
  }
  this.length = arr.length
  for (let i = 0; i < this.length; i++) {
    this[i] = arr[i]
  }
  const len = this.length + temp.length
  let j = 0
  for (let i = arr.length; i < len; i++) {
    this[i] = temp[j]
    j++
  }
  return len
}
Copy the code

The last

It took three months to finish writing almost all methods in two articles, and I was lazy for two months in the middle. After writing the harvest is not small, especially in the project when it is used, no longer need to turn over the document to find the method of use and matters needing attention, just use!

To be honest, I did not add any new knowledge from the beginning to the end, and then I did not say how perfect and good the method, but after writing whether the interviewer asked or used will become easy to use. That’s the end of it.

The first article here is a brief description of all the built-in methods of the JS array and the manual implementation (a).

All source code on GITHUB, welcome Star.

If there are any shortcomings or mistakes, readers are welcome to comment and leave a message

Of course, if this article is of any help to you, please like and retweet it. Thank you 🙏