Detailed explanation of native array method in JavaScript

Time:2021-3-1

In JS, arrays can be constructed by array constructor or[]Literal quantity. Array is a special object, inherited from the object prototype. However, when typeof is used to judge, it does not have a specific value and still returns’ object ‘. But use the [] instanceof array to return true. This shows that there is an object of class array in JS, just like string object or arguments object. The arguments object is not an instance of an array, but it still has the length attribute. The value can also be indexed, so it can be iterated like an array.

In this article, I will review some common methods defined on the array prototype, and introduce their usage one by one.

  • Loop.foreach
  • Assertion. Some,. Every
  • Join,. Concat
  • Stack and queue. Pop,. Push,. Shift,. Unshift
  • Model mapping.map
  • Filter.filter
  • Sort.sort
  • Aggregate. Reduce,. Reducereight
  • Intercept.slice
  • Delete insert.splice
  • Find value.indexof
  • Find key in operator
  • Reverse

native-array-functions

1.forEach()

Foreach executes the parameter function for all members of the array in turn and only once. The parameter function contains the following three parameters:

  • Value current value
  • Index current position, index value
  • Array current array

Furthermore, an optional parameter can be passed to specify the this context in the function.

['_', 't', 'a', 'n', 'i', 'f', ']'].forEach(function (value, index, array) {
    this.push(String.fromCharCode(value.charCodeAt() + index + 2))
}, out = [])

out.join('')
//

The drawback of foreach is that it can neither break the loop nor throw an exception.

2.some(), every()

These two methods are similar to “assert”, and return a Boolean value to judge whether the array members meet certain conditions.
Similar to foreach, it also accepts a callback function containing value, index, and array as a parameter, and can also specify this in the context.
The return value of some method is true as long as the return value of one member is true, otherwise it returns false.
Every method returns true only when all members return true. Otherwise, it returns false.

max = -Infinity
satisfied = [10, 12, 10, 8, 5, 23].some(function (value, index, array) {
    if (value > max) max = value
    return value < 10
})

console.log(max)
//

3.join() and concat()

These two methods are easy to confuse. Join is to connect the members of an array into a string with a separator. The default separator is,, concat, which is used to merge multiple arrays. It adds the members of the new array to the back of the original array members, and then returns a new array with the original array unchanged.

var a = { foo: 'bar' }
var b = [1, 2, 3, a]
var c = b.concat()

console.log(b === c)
//

4.pop, .push, .shift, and .unshift

Everyone knows that adding an element to the end of an array is a push method, but did you know that you can add more than one element at a time, like this[].push('a', 'b', 'c', 'd', 'z').
Pop is the reverse operation of the push method, which removes the last element of the array and returns it at the same time. If it is an empty array, it returns undefined. Using these two methods, it is easy to implement the LIFO (last in first out) stack structure.

function Stack () {
    this._stack = []
}

Stack.prototype.next = function () {
    return this._stack.pop()
}

Stack.prototype.add = function () {
    return this._stack.push.apply(this._stack, arguments)
}

stack = new Stack()
stack.add(1,2,3)

stack.next()
//

Correspondingly, we can implement a FIFO (first in first out) queue through. Unshift and. Shift.

function Queue () {
    this._queue = []
}

Queue.prototype.next = function () {
    return this._queue.shift()
}

Queue.prototype.add = function () {
    return this._queue.unshift.apply(this._queue, arguments)
}

queue = new Queue()
queue.add(1,2,3)

queue.next()
//

With. Shift (or. Pop), it’s easy to empty an array with a while loop, as follows:

list = [1,2,3,4,5,6,7,8,9,10]

while (item = list.shift()) {
    console.log(item)
}

list
//

5.map()

The map method passes all the members of the array into the callback function in turn, and then returns each execution result into a new array.
Method signatures are similar toforEach,.map(fn(value, index, array), thisArgument).

values = [void 0, null, false, '']
values[7] = void 0
result = values.map(function(value, index, array){
    console.log(value)
    return value
})
//

Undefined × 3 indicates that the callback function will not be executed in the deleted or unassigned members, but will return itself and be included in the return array. Map is very useful for mapping or converting arrays, such as the following example:

// casting
[1, '2', '30', '9'].map(function (value) {
    return parseInt(value, 10)
})
// 1, 2, 30, 9

[97, 119, 101, 115, 111, 109, 101].map(String.fromCharCode).join('')
//

6.filter()

The filter method is used to filter array members, and the members that meet the conditions form a new array to return.

Using a,.filter(fn(value, index, array), thisArgument).

[void 0, null, false, '', 1].filter(function (value) {
    return value
})
//

7.sort(compareFunction)

The sort method sorts the array members. By default, it is sorted in dictionary order. After sorting, the original array will be changed.
Like most sort functions, Array.prototype.sort (FN (a, b)) accepts a callback function to compare the sizes of a and B, and is one of the following three cases:

  • return value < 0 if a comes before b
  • return value === 0 if both a and b are considered equivalent
  • return value > 0 if a comes after b
[9,80,3,10,5,6].sort()
//

8.reduce(), reduceRight()

Reduce functions are difficult to understand at the beginning. These functions will loop through the array, from left to right (. Reduce) or from right to left (. Reducereight). Each time the callback function is executed, some of the previous results will be accepted, and the final return value is a single aggregate value.

The two methods have the same syntax:

reduce(callback(previousValue, currentValue, index, array), initialValue)

Previousvalue is the return value of the last callback function execution, or the initial value of the first execution; currentvalue is the current value; index is the current value position; array is the reference to the array of reduce methods; initialvalue is the initial value; and;

A typical application scenario of. Reduce method is the summation of array members

Array.prototype.sum = function () {
    return this.reduce(function (partial, value) {
        return partial + value
    }, 0)
};

[3,4,5,6,10].sum()
//

9.slice()

Slice () method is used to extract part of the target array and return a new array, the original array remains unchanged.

arr.slice(start, end)

Its first parameter is the starting position (from 0, it will be included in the new array returned), and its second parameter is the ending position (but the elements of this position are not included). If the second parameter is omitted, it is returned to the last member of the original array.

Similar to concat(), slice() returns a shallow copy of the original array without any parameters. Array.prototype.slice It can be used to convert objects of class array to real array.

Array.prototype.slice.call({ 0: 'a', 1: 'b', length: 2 })
//

If concat fails, it returns an array containing the incoming objects.

Array.prototype.concat.call({ 0: 'a', 1: 'b', length: 2 })
//

10.splice()

. splice is my favorite array native array method. It allows you to delete and insert elements in the same location at one time. Note: this function will change the original array.

var source = [1,2,3,8,8,8,8,8,9,10,11,12,13]
var spliced = source.splice(3, 4, 4, 5, 6, 7)

console.log(source)
//

You may have noticed that it will return the deleted element, which is often used to loop the deleted element. You may have forgotten before.

var source = [1,2,3,8,8,8,8,8,9,10,11,12,13]
var spliced = source.splice(9)

spliced.forEach(function (value) {
    console.log('removed', value)
})
//

11.indexOf()、lastIndexOf()

The indexof method returns the position of the first occurrence of the given element in the array. If it does not appear, it returns – 1.

var a = { foo: 'bar' }
var b = [a, 2]

console.log(b.indexOf(1))
//

The lastIndexOf method returns the position of the last occurrence of the given element in the array. If it does not appear, it returns – 1.

Note that these two methods cannot be used to search the location of Nan, that is, they cannot determine whether an array member contains Nan.

This is because inside the two methods, the strict equality operator (= = =) is used for comparison, while Nan is the only value that is not equal to itself.

12. In operator

In is used to find out whether the key exists in an array, and indexof is the search value. Of course, it’s faster than indexof

var a = [1, 2, 5]

1 in a
//
var a = [3, 7, 6]

1 in a === !!a[1]
//

The in operator is similar to converting the value of the corresponding position to a Boolean value. !! Expressions are often used to negate a value and then negate it, which is an efficient way to convert a truth value into a Boolean value.

13.reverse()

The reverse method is used to invert the array elements and return the changed array. Note that this method changes the original array.

var a = ['a', 'b', 'c'];

a.reverse() // ["c", "b", "a"]

a // ["c", "b", "a"]