Summary of common methods of ES5 and ES6 arrays

ES5 common methods

1. Stack method (LIFO) last in first out:

push() adds an element to the end of the array

pop() removes the element from the end of the array and returns it, while the length of the array is reduced by 1

var arr = [1,2,3]
arr.push(4)//arr = [1,2,3,4]
var b = arr.pop()//4

 

2. Queue method (FIFO) first in first out

shift() removes the first element of the array and returns it. At the same time, the length of the array is reduced by 1

unshift() adds an element to the header of the array

 

var arr = [1,2,3]
var b = arr.shift()//1
arr.unshift(1)//arr = [1,2,3,]

3. Array reordering method

reverse() reverses the array order

sort() sorts the array in ascending order

//reverse()Reverse array order
var arr = [1,2,3]
var b = arr.reverse()//[3,2,1]

//sort() Execute each item of the array toString()Method, and then compare the obtained strings and sort them from small to large
var arr = [1,3,5,25,15]
var b = arr.sort() //  [1, 15, 25, 3, 5]
//This result is obviously not what we want, sort()You can take a comparison function as an argument so that we can specify which value precedes which value
function compare(value1,value2){
  return value1 - value2
}
var arr = [1,3,5,25,15]
var b = arr.sort(compare) //  [1, 3,5,15,25]

4. Operation method of array

concat() creates a copy based on all items of the current array, adds the accepted parameters to the tail of the copy array, and returns a new array without affecting the original array

 

var arr = [1,2,3]
var b = arr.concat([4,5],'6') // [1, 2, 3, 4, 5, "6"]

 

slice() creates a copy based on some items of the current array and returns a new array without affecting the original array

 

 

var arr = [1,2,3,4,5]
var b = arr.slice() //[1, 2, 3, 4, 5]
var c = arr.slice(1,) //[2, 3, 4, 5]
var d = arr.slice(1,4) //[2, 3, 4]

 

splice() deletes (can not be deleted) consecutive items in the array and inserts (can not be inserted) other items. It returns the deleted items and changes the original array

 

 

//First parameter---The location where you want to delete the first item
//Second parameter---Number of items to delete
//Third and subsequent parameters---Item to insert
var arr = [1,2,3,4,5]
var b = arr.splice(0,1) // arr = [2,3,4,5] b = [1]
var c = arr.splice(1,2,7,8) // arr = [2,7,8,5] c = [3,4]
var d = arr.splice(1,0,9,0) // arr = [2,7,9,0,8,5] d = []

5. Location method

indexOf() searches for an item from the array header, and returns the index value of the item found for the first time. If it is not found, it returns - 1. This method accepts two parameters. The index value of the starting point of the search, and the item to be searched.

lastIndexOf() searches for an item from the end of the array, and returns the index value of the item found for the first time. If it is not found, it returns - 1. This method accepts two parameters. The index value of the starting point of the search, and the item to be searched.

6. Iterative method

The following methods all accept three parameters: the array item, the index value of the item, and the array itself

  • forEach() -- run the given function for each item in the array, and this method has no return value;
  • map() -- execute the given function for each item in the array and return the new array composed of the function execution result, which does not affect the original array;
  • filter() -- execute the given function on each item in the array and return the new array formed by the function execution result of true, which will not affect the original array;
  • every() -- execute the given function for each item of the array. If the execution result of the function is true, return true; otherwise, return false;
  • some() -- execute the given function for each item of the array. If the result of one item is true, it will return true.
//forEach
var arr = [1,2,3,4]
arr.forEach((item,index,array)=>{
  //Some operations
})

//map
arr = [1,2,3,4]
var b = arr.map((item,index,array)=>{
  return item*2
})
//b = [2, 4, 6, 8]

//filter
arr = [1,2,3,4]
var d = arr.filter((item,index,array)=>{
  return item > 3
})
//d = [4]

//every
arr = [1,2,3,4]
var e = arr.every((item,index,array)=>{
  return item > 3
})
//e = false

//some
arr = [1,2,3,4]
var f = arr.some((item,index,array)=>{
  return item > 3
})
//some = true

6. Merging method

reduce() traverses the array one by one from the first item of the array and returns the execution result of the given function

reduceRight() traverses the array one by one from the first item of the array and returns the execution result of the given function

The method accepts two parameters: 1. The function called by each item; 2. Optional initial value as the basis of merging; The function passed to this method accepts four parameters, the previous value, current value, index item and array object. Any value returned by this function will be automatically passed to the next item as the first parameter. The first iteration occurs in the second item of the array. Therefore, the first input parameter is the first item of the array and the second input parameter is the second item of the array.

var arr = [1,2,3,4,5]
var b = arr.reduce((prev,cur,index,array)=>{
  return prev + cur
})
// b = 15

var arr = [1,2,3,4,5]
var b = arr.reduce((prev,cur,index,array)=>{
  return prev + cur
},4)
//b = 19

ES6 common methods

1. form(): convert array like objects and iteratable objects into real arrays

 

let arrayLike = {
    '0': 'a',
    '1': 'b',
    '2': 'c',
    length: 3
};

// ES5 Writing method of
var arr1 = [].slice.call(arrayLike); // ['a', 'b', 'c']

// ES6 Writing method of
let arr2 = Array.from(arrayLike); // ['a', 'b', 'c']

As long as the data structure of the Iterator interface is deployed, array From can be converted into an array.

Array.from('hello')
// ['h', 'e', 'l', 'l', 'o']

let namesSet = new Set(['a', 'b'])
Array.from(namesSet) // ['a', 'b']

It is worth reminding that the extension operator (...) You can also convert some data structures into arrays.

// arguments object
function foo() {
  var args = [...arguments];
}

// NodeList object
[...document.querySelectorAll('div')]

Behind the extension operator is the traversal interface (Symbol.iterator). If an object does not deploy this interface, it cannot be converted. Array. The from method also supports objects similar to arrays. The so-called array like object has only one essential feature, that is, it must have the length attribute. Therefore, any object with the length attribute can be accessed through array The from method is converted to an array, and the extension operator cannot be converted at this time.

For browsers that have not deployed this method, you can use array prototype. Slice method substitution.

const toArray = (() =>
  Array.from ? Array.from : obj => [].slice.call(obj)
)();

Array.from can also accept the second parameter, which is similar to the map method of array. It is used to process each element and put the processed value into the returned array.

Array.from(arrayLike, x => x * x);
// Equivalent to
Array.from(arrayLike).map(x => x * x);

Array.from([1, 2, 3], (x) => x * x)
// [1, 4, 9]

2. of() converts a set of values into an array

Array.of(3, 11, 8) // [3,11,8]
Array.of(3) // [3]
Array.of(3).length // 1

Array() // []
Array(3) // [, , ,]
Array(3, 11, 8) // [3, 11, 8]

//Array When the method has no parameters, one parameter or three parameters, the returned results are different. Only when the number of parameters is not less than 2, Array()Will return a new array of parameters. When there is only one parameter, it actually specifies the length of the array.

//Array.of Basically can be used to replace Array()or new Array(),And there is no overload caused by different parameters. Its behavior is very uniform.
Array.of() // []
Array.of(undefined) // [undefined]
Array.of(1) // [1]
Array.of(1, 2) // [1, 2]

Array. The of method can be simulated and implemented with the following code.

function ArrayOf(){
  return [].slice.call(arguments);
}

3. Method of array real column: copyWith() in the current array, copy the specified members to other locations (the original members will be overwritten), and then return to the current array. This method will modify the current array.

 

Array.prototype.copyWithin(target, start = 0, end = this.length)

 

He accepts three parameters:

  • target (required): replace data from this location.
  • Start (optional): start reading data from this location. The default value is 0. If it is negative, it means the reciprocal.
  • end (optional): stop reading data before reaching this position, which is equal to the length of the array by default. If it is negative, it means the reciprocal.
[1, 2, 3, 4, 5].copyWithin(0, 3)
// [4, 5, 3, 4, 5]
// Copy position 3 to position 0
[1, 2, 3, 4, 5].copyWithin(0, 3, 4)
// [4, 2, 3, 4, 5]

// -2 Equivalent to position 3,-1 Equivalent to position 4
[1, 2, 3, 4, 5].copyWithin(0, -2, -1)
// [4, 2, 3, 4, 5]

// Copy position 3 to position 0
[].copyWithin.call({length: 5, 3: 1}, 0, 3)
// {0: 1, 3: 1, length: 5}

// Copy position 2 to the end of the array and to position 0
var i32a = new Int32Array([1, 2, 3, 4, 5]);
i32a.copyWithin(0, 2);
// Int32Array [3, 4, 5, 4, 5]

// No deployment for TypedArray of copyWithin Method platform
// It needs to be written in the following way
[].copyWithin.call(new Int32Array([1, 2, 3, 4, 5]), 0, 3, 4);
// Int32Array [4, 2, 3, 4, 5]

4. find() and findIndex() of array instances

find() is used to find the first qualified array member. Its parameter is a callback function. All members execute the callback function in turn until the first member with a return value of true is found, and then return the member. If there are no qualified members, undefined is returned.

 

[1, 5, 10, 15].find(function(value, index, arr) {
  return value > 9;
}) // 10

 

The callback function of the find method can accept three parameters: the current value, the current position and the original array.

The usage of findIndex method is very similar to that of find method. It returns the position of the first qualified array member. If all members do not meet the conditions, it returns - 1.

 

[1, 5, 10, 15].findIndex(function(value, index, arr) {
  return value > 9;
}) // 2

 

5,fill()

Fills an array with the given value

 

['a', 'b', 'c'].fill(7)
// [7, 7, 7]

new Array(3).fill(7)
// [7, 7, 7]

//fill Method can also accept the second and third parameters to specify the start and end positions of the fill.
['a', 'b', 'c'].fill(7, 1, 2)
// ['a', 7, 'c']

 

6. Entries(), keys() and values() - used to traverse the array. They all return an Iterator object (see the chapter "Iterator" for details). You can use for The only difference is that keys() traverses key names, values() traverses key values, and entries() traverses key value pairs.

 

for (let index of ['a', 'b'].keys()) {
  console.log(index);
}
// 0
// 1

for (let elem of ['a', 'b'].values()) {
  console.log(elem);
}
// 'a'
// 'b'

for (let [index, elem] of ['a', 'b'].entries()) {
  console.log(index, elem);
}
// 0 "a"
// 1 "b"

//If not used for...of Loop, you can manually call the next Method to traverse.

let letter = ['a', 'b', 'c'];
let entries = letter.entries();
console.log(entries.next().value); // [0, 'a']
console.log(entries.next().value); // [1, 'b']
console.log(entries.next().value); // [2, 'c']

 

Posted by barteelamar on Fri, 06 May 2022 23:53:24 +0300