Push – Affects the original array

Definition: Adds one or more elements to the end of an array and returns the new length of the array. (Affects the original array)

Grammar:

arr.push(element1, … , elementN)

Parameters:

  • ElementN: The element added to the end of the array.

Return value: Returns the new length of the array.

Implementation process:

Array.prototype._push = function () {
  var length = this.length;
  for (var i = 0; i < arguments.length; i++) {
    this[length + i] = arguments[i];
  }
  return this.length;
}
Copy the code

Pop – Affects the original array

Definition: Removes the last element from an array and returns the value of that element. (Affects the original array)

Grammar:

arr.pop()

Parameters: no

Return value: Returns the element removed from the array, or undefined if the array is empty.

Implementation process:

Array.prototype._pop = function () { if (! this.length) return; var lastItem = this[this.length - 1]; this.length = this.length - 1; return lastItem; }Copy the code

Unshift – Affects the original array

Definition: Adds one or more elements to the beginning of an array and returns the new length of the array. (Affects the original array)

Grammar:

arr.unshift(element1, … , elementN)

Parameters:

  • ElementN: The element or elements to be added to the beginning of an array.

Return value: Returns the new length of the array.

Implementation process:

Array.prototype._unshift = function () { var len = arguments.length; Var loopNum = this.length + len-1; var loopNum = this.length + len-1; For (var I = loopNum; i >= 0; If (I >= len) {this[I] = this[i-len]; if (I >= len) {this[I] = this[i-len]; } else { this[i] = arguments[i]; } } return this.length; }Copy the code

We know that the length of the new array is equal to the length of the original array + the number of elements added. We can loop through the length of the new array in reverse order, sorting the elements of the original array first and then the elements of the new array, but taking the elements of the original array in reverse order. When the number of times left in the loop is less than the number of elements added, it means that the elements of the original array are arranged in the new array.

Shift – Affects the original array

Definition: Removes the first element from an array and returns the value of that element. (Affects the original array)

Grammar:

arr.shift()

Parameters: no

Return value: Returns the element removed from the array, or undefined if the array is empty.

Implementation process:

Array.prototype._shift = function () { if (! this.length) return; var firstItem = this[0]; for (var i = 1; i < this.length; i++) { this[i - 1] = this[i]; } this.length = this.length - 1; return firstItem; }Copy the code

Reverse – Affects the original array

Definition: 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. (Affects the original array)

Grammar:

arr.reverse()

Parameters: no

Return value: Returns the reversed array.

Implementation process:

Array.prototype._reverse = function () {
  var temp = undefined;
  var loopNum = parseInt(this.length / 2);
  for (var i = 0; i < loopNum; i++) {
    temp = this[i];
    this[i] = this[this.length - 1 - i];
    this[this.length - 1 - i] = temp;
  }
  return this;
}
Copy the code

Splice – Affects the original array

Definition: To modify an array by removing or replacing existing elements or adding new ones in place, and return the modified contents as an array. (Affects the original array)

Grammar:

array.splice(start[, deleteCount[, item1[, item2[, …]]]])

Parameters:

  • Start: Specifies the start 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.

  • DeleteCount (Optional) : Integer representing the number of array elements to remove. 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.

  • item1, item2, … (Optional) : The element to add to the array, starting at the start position. If not specified, splice() will delete only array elements.

Return value: Returns an array of deleted elements. If only one element is removed, an array containing only one element is returned. If no element is deleted, an empty array is returned.

Implementation process:

Array.prototype._splice = function (startIndex, deleteCount, ... addElements) { let argumentsLen = arguments.length; let array = Object(this); let len = array.length; let deleteArr = new Array(deleteCount); startIndex = computeStartIndex(startIndex, len); deleteCount = computeDeleteCount(startIndex, len, deleteCount, argumentsLen); If (object.issealed (array) && deleteCount! == addElements.length) { throw new TypeError('the object is a sealed object! ') } else if (Object.isFrozen(array) && (deleteCount > 0 || addElements.length > 0)) { throw new TypeError('the object is a frozen object! SliceDeleteElements (array, startIndex, deleteCount, deleteArr); MovePostElements (array, startIndex, len, deleteCount, addElements); // Insert a new element for (let I = 0; i < addElements.length; i++) { array[startIndex + i] = addElements[i]; } array.length = len - deleteCount + addElements.length; return deleteArr; }Copy the code

Parsing process: this method can be said to be one of the most complex array methods, specific details can refer to this article, click me, read the basic can understand, write very nice.

join

Definition: Concatenates all the elements of an array (or an array-like object) into a string and returns the string. If the array has only one item, that item is returned without a delimiter.

Grammar:

arr.join([separator])

Parameters:

  • Separator (Optional) : Specifies a string to separate each element of the array. The default is to convert the splitter to a string. If not filled in orundefinedIs separated by commas by default. If is an empty string (""), there are no characters between all elements.

Return value: Returns a string connected to all array elements. If arr.length is 0, an empty string is returned.

Implementation process:

Array.prototype._join = function(separator) { if(this.length === 0) return ''; if(separator === undefined) separator = ','; var resultStr = this[0] + ''; for(var i = 1; i<this.length; i++) { resultStr += separator + this[i]; } return resultStr; }Copy the code

concat

Definition: Used to merge two or more arrays and return a new array.

Grammar:

var new_array = old_array.concat(value1[, value2[, …[, valueN]]])

Parameters:

  • ValueN: Arrays and/or values that will be merged into a new array. If there is no parameter, theconcatReturns a shallow copy of the existing array that called the method.

Return value: Returns a new array

Implementation process:

Array.prototype._concat = function () { var result = JSON.parse(JSON.stringify(this)); for (var i = 0; i < arguments.length; i++) { var item = arguments[i]; If (array.isarray (item)) {// If (array.isarray (item)) {for (var j = 0; j < item.length; j++) { result[result.length] = item[j]; } } else { result[result.length] = arguments[i]; } } return result; }Copy the code

indexOf

Definition: Returns the first index in the array where a given element can be found, or -1 if none exists.

Grammar:

arr.indexOf(searchElement[, fromIndex])

Parameters:

  • SearchElement: The element to find.
  • FromIndex (Optional) : Start the search. If the index value is greater than or equal to the length of the array, it means that it is not searched in the array, and returns -1. If the index value provided in the argument is a negative value, it is treated as an offset at the end of the array, with -1 indicating the search starts from the last element, -2 indicating the search starts from the next-to-last element, and so on. Note: If the index value provided in the argument is a negative value, the lookup order does not change, and the lookup order is still the array queried from front to back. If the offset index is still less than 0, the entire array will be queried. The default value is 0.

Return value: returns the index position of the first found element in the array; If none is found, -1 is returned.

Implementation process:

Array.prototype._indexOf = function (searchElement, fromIndex) { var index = -1; if (! fromIndex) fromIndex = 0; // fromIndex: 0 || "" || null || undefined if (typeof fromIndex ! == 'number' && typeof fromIndex ! == 'string') fromIndex = 0; If (typeof fromIndex === 'string' && Typeof parseInt(fromIndex)! == 'number') fromIndex = 0; If (fromIndex < 0) fromIndex = this.length - (fromIndex * -1); for (var i = parseInt(fromIndex); i < this.length; i++) { if (searchElement === this[i]) return i; } return index; }Copy the code

Analysis process: There are two main troublesome points in this method. The first is the judgment of the type of fromIndex, and the second is the case when fromIndex is negative. I’ll just draw a picture for you and I’ll give you a little example to make sense of it.

var arr = [1, 2, 3, 4, 2, 5]; arr.indexOf(2, -1); // -1 arr.indexOf(2, -2); / / 4Copy the code

As in the above example, arr.indexof (2, -1); It finds -1 and then it looks in the direction it was looking for, which is to the right, and there’s only one 5 left, so it doesn’t find 2 and it returns -1; The arr. IndexOf (2, 1); It finds -2 and looks to the right. It finds 2 and 5,2 matches the target, so it returns the index value of 2, 4.

reduce

Definition: Execute a Reducer function (in ascending order) that you provide on each element in the array and summarize its results into a single return.

Grammar:

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

Parameters:

  • Callback: a function that executes each value in the array (except the first value if no initialValue is provided), with four arguments:
    • Accumulator: The return value of the accumulator callback; It is the cumulative value, or initialValue, returned when the callback was last invoked (see below).
    • CurrentValue: The element being processed in the array.
    • Index (Optional) : Index of the current element being processed in the array. If initialValue is provided, the starting index is 0, otherwise it starts from index 1.
    • Array (Optional) : Array to call reduce().
  • InitialValue (Optional) : The value of the first argument when the callback function is called for the first time. If no initial value is provided, the first element in the array is used. Calling reduce on an empty array with no initial value will report an error.

Return value: cumulative processing result of the function.

Implementation process:

Array.prototype._reduce = function (cb, initialValue) { if (typeof cb ! == 'function') throw new TypeError(cb + ' is not a function'); if (this.length === 0 && initialValue === undefined) throw new TypeError('Reduce of empty array with no initial value');  var total = 0; var index = 0; if (initialValue ! == undefined) { total = initialValue; } else { total = this[0]; index = 1; } for (var i = index; i < this.length; i++) { total = cb(total, this[i], i, this); } return total; }Copy the code

forEach

Definition: Executes a given function on each element of an array once.

Grammar:

arr.forEach(callback(currentValue [, index [, array]])[, thisArg])

Parameters:

  • The callback:
    • CurrentValue: current traversal element.
    • Index (Optional) : indicates the current traversal index.
    • Array (Optional) : indicates the array itself.
  • ThisArg (optional) : ExecutecallbackWhen the callback function is inside the callback functionthisValue.

Return value: return undefined.

Implementation process:

Array.prototype._forEach = function (cb, thisArg) {
  if (typeof cb !== 'function') throw new TypeError(cb + ' is not a function');
  for (var i = 0; i < this.length; i++) {
    cb.call(thisArg, this[i], i, this);
  }
}
Copy the code

map

Definition: Creates a new array with the result that each element in the array is the value returned by calling the supplied function once.

Grammar:

var new_array = arr.map(function callback(currentValue[, index[, array]]) {

// Return element for new_array

}[, thisArg])

Parameters:

  • The callback:
    • CurrentValue: current traversal element.
    • Index (Optional) : indicates the current traversal index.
    • Array (Optional) : indicates the array itself.
  • ThisArg (optional) : ExecutecallbackWhen the callback function is inside the callback functionthisValue.

Return value: Returns a new array consisting of the result of each element of the original array executing the callback function.

Implementation process:

Array.prototype._map = function (cb, thisArg) { if (typeof cb ! == 'function') throw new TypeError(cb + ' is not a function'); var result = []; for (var i = 0; i < this.length; i++) { result.push(cb.call(thisArg, this[i], i, this)); } return result; }Copy the code

filter

Definition: Creates a new array that contains all the elements of the tests implemented by the provided function.

Grammar:

var newArray = arr.filter(callback(element[, index[, array]])[, thisArg])

Parameters:

  • The callback:
    • Element: The element currently traversed.
    • Index (Optional) : indicates the current traversal index.
    • Array (Optional) : indicates the array itself.
  • ThisArg (optional) : ExecutecallbackWhen the callback function is inside the callback functionthisValue.

Return value: Returns a new array of elements that pass the test, or an empty array if none of the array elements pass the test.

Implementation process:

Array.prototype._filter = function (cb, thisArg) { if (typeof cb ! == 'function') throw new TypeError(cb + ' is not a function'); var result = []; for (var i = 0; i < this.length; i++) { if (cb.call(thisArg, this[i], i, this)) { result.push(this[i]); } } return result; }Copy the code

some

Definition: Tests whether at least 1 element in the array passes the provided function test. It returns a Boolean. If you test with an empty array, it returns false in all cases.

Grammar:

arr.some(callback(element[, index[, array]])[, thisArg])

Parameters:

  • The callback:
    • Element: The element currently traversed.
    • Index (Optional) : indicates the current traversal index.
    • Array (Optional) : indicates the array itself.
  • ThisArg (optional) : ExecutecallbackWhen the callback function is inside the callback functionthisValue.

Return value: True if one of the array items passes the test function, false otherwise,

Implementation process:

Array.prototype._some = function (cb, thisArg) { if (typeof cb ! == 'function') throw new TypeError(cb + ' is not a function'); for (var i = 0; i < this.length; i++) { if (cb.call(thisArg, this[i], i, this)) return true; } return false; }Copy the code

every

Definition: Tests whether all elements in an array pass the test of a specified function. It returns a Boolean value. If an empty array is received, this method returns true in all cases.

Grammar:

arr.every(callback(element[, index[, array]])[, thisArg])

Parameters:

  • The callback:
    • Element: The element currently traversed.
    • Index (Optional) : indicates the current traversal index.
    • Array (Optional) : indicates the array itself.
  • ThisArg (optional) : ExecutecallbackWhen the callback function is inside the callback functionthisValue.

Return value: True if all elements pass the test function, false otherwise.

Implementation process:

Array.prototype._every = function (cb, thisArg) { if (typeof cb ! == 'function') throw new TypeError(cb + ' is not a function'); for (var i = 0; i < this.length; i++) { if (! cb.call(thisArg, this[i], i, this)) return false; } return true; }Copy the code

find

Definition: Returns the value of the first element in the array that satisfies the provided test function. Otherwise return undefined.

Grammar:

arr.find(callback[, thisArg])

Parameters:

  • The callback:
    • Element: The element currently traversed.
    • Index (Optional) : indicates the current traversal index.
    • Array (Optional) : indicates the array itself.
  • ThisArg (optional) : ExecutecallbackWhen the callback function is inside the callback functionthisValue.

Return value: Returns the value of the first element in the array that satisfies the provided test function, otherwise undefined.

Implementation process:

Array.prototype._find = function (cb, thisArg) { if (typeof cb ! == 'function') throw new TypeError(cb + ' is not a function'); for (var i = 0; i < this.length; i++) { if (cb.call(thisArg, this[i], i, this)) return this[i]; } return; }Copy the code

findIndex

Definition: Returns the index of the first element in the array that satisfies the provided test function, or -1 if no corresponding element is found.

Grammar:

arr.findIndex(callback[, thisArg])

Parameters:

  • The callback:
    • Element: The element currently traversed.
    • Index (Optional) : indicates the current traversal index.
    • Array (Optional) : indicates the array itself.
  • ThisArg (optional) : ExecutecallbackWhen the callback function is inside the callback functionthisValue.

Return value: Returns the index of the first element in the array tested by the callback function, otherwise -1.

Implementation process:

Array.prototype._findIndex = function (cb, thisArg) { if (typeof cb ! == 'function') throw new TypeError(cb + ' is not a function'); for (var i = 0; i < this.length; i++) { if (cb.call(thisArg, this[i], i, this)) return i; } return -1; }Copy the code

At this point, this article is finished, sa Hua Sa hua.

I hope this article has been helpful to you. If you have any questions, I am looking forward to your comments. Same old, likes + comments = you know it, favorites = you know it.