JavaScript Array objects are global objects used to construct arrays, which are higher-order objects similar to lists.

for

For is not an array-specific method

For is a javaScript specific statement

for(let i = 0; i<numberList.length; i++) { console.log('numberList[i]---------',numberList[i]) }Copy the code

forEach

Run the given function on each item in the array

This method does not return a value

Callback (currentValue [, index [, array]])[, thisArg])

  • This function takes the current value of the array, the index of the current item of the array, and the array object itself

    numberList.forEach(function(element, index, array) { console.log(‘array—————–‘,array); console.log(‘index—————–‘,index); console.log(‘element—————–‘,element); })

map

Run the given function on each item in the array

This method returns a new array of the results of each function call

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

// Return element for new_array }[, thisArg])

  • Receives a function callback that takes three arguments: currentValue, index, and array

  • CurrentValue: The current element being processed in the callback array

  • Index: Index of the current element being processed in the callback array.

  • Array: array called by the map method.

    let newArray = numberList.map(function(element, index, array) { return ! element ? 0 : element + 1 })

concat

Concatenate two or more arrays and return the result

This method does not change an existing array, but returns a new array

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

  • Concat joins two arrays: let numberList_2 = [12, 13, 14, 15, 16, 17, 18];

    let numberList_3 = []
    numberList_3 = numberList_3.concat(numberList, numberList_2);
    console.log('numberList_3-----------------', numberList_3);
    Copy the code
  • Concatenate values to arrays: let alpha = [‘a’, ‘b’, ‘c’];

    let alphaNumeric = alpha.concat(1, [2, 3]); console.log(alphaNumeric); // results in ['a', 'b', 'c', 1, 2, 3]Copy the code

filter

Run the given function on each item in the array

This method returns an array of true items

Var newArray = callback(Element [, index[, array]])[, thisArg])

  • This method takes a function callback and three arguments: Element, index, and array

  • Element: The element in the array currently being processed

  • Index: Index of the element being processed in the array

  • Array: calls the array itself of filter

  • Example:

    let filtered = [12, 5, 8, 130, 44].filter(function (element) {

    return element >= 10;

    });

every

Run the given function on each item in the array

Returns true if the function returns true for each item

If an empty array is received, this method returns true in all cases.

Every () does not change the array

Arr. Every (element[, index[, array]])[, thisArg])

  • This method receives a function callback that tests each element’s function and takes three arguments: Element, index, and array

  • Element: Current value for testing.

  • Index: Index of the current value used for testing

  • Array: The current array that calls every

    let everyResult = [12, 54, 18, 130, 44].every(function (element, index, array) { return element >= 10 })

some

The some() method tests that at least one element in the array passes the provided function test and returns a Boolean value.

Run the given function on each item in the array

Returns true if either item returns true

Note: If you test with an empty array, it returns false in any case.

Some () is called without changing the array.

Arr. Some (element[, index[, array]])[, thisArg])

  • This method receives a function callback that tests each element’s function and takes three arguments: Element, index, and array

  • Element: The element being processed in the array

  • Index: The index value of the element being processed in the array.

  • Array: the array in which some() is called.

    let someResult = [2, 5, 8, 1, 4].some(function(element, index, array) { return element > 10; }) console.log(‘someResult———‘, someResult)

from

This method creates a new, shallow-copy array instance from an array-like or iterable

Array.from(arrayLike[, mapFn[, thisArg]])

  • This method receives an arrayLike, mapFn, thisArg

  • ArrayLike: A pseudo-array object or iterable that you want to convert to an array.

  • MapFn: If specified, each element in the new array will execute the callback function.

  • ThisArg: Optional argument, this object when the callback function mapFn is executed.

MapFn is an optional argument that can be returned after the map method is executed again on the last generated array.

Array.from(obj, mapFn, thisArg) = array. from(obj).map(mapFn, thisArg)

Generate an array from Sting

let fromResult = Array.from('123213')
Copy the code

Generate an array from a Set to implement array de-duplication

const set = new Set(['foo', 'bar', 'baz', 'foo']); Array.from(set); // [ "foo", "bar", "baz" ]Copy the code

of

Creates a new array instance with a variable number of parameters

Array. Of (element0[, element1[,…[, elementN]])

  • ElementN: Any arguments that will become elements in the returned array in that order.

The difference between array.of () and Array constructors is that they handle integer arguments

Array.of(7); // [7] Array.of(1, 2, 3); // [1, 2, 3] Array(7); // [ , , , , , , ] Array(1, 2, 3); / / [1, 2, 3]Copy the code

Returns a new Array instance.

indexOf

The indexOf() method returns the first index in the array where a given element can be found, or -1 if none exists.

This method retrieves the array from beginning to end to see if it contains the corresponding element

Syntax: arr.indexof (searchElement[, fromIndex])

  • SearchElement The element to find

  • FromIndex starts 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.

// Find all the places where the specified element appears

var indices = []; var array = ['a', 'b', 'a', 'c', 'a', 'd']; var element = 'a'; var idx = array.indexOf(element); if(idx == -1) { indices = []; } while (idx ! = -1) { indices.push(idx); idx = array.indexOf(element, idx + 1); } console.log('indices-------',indices);Copy the code

lastIndexOf

The lastIndexOf() method returns the last occurrence of the index in which a given element was found in the array, and the index of the given element, or -1 if none exists (looking forward from the back of the array, starting at fromIndex).

This method retrieves the array from end to end to see if it contains the corresponding element

The index of the starting position is 0.

Syntax: arr. LastIndexOf (searchElement[, fromIndex])

  • Start looking backwards from this location

  • SearchElement: Element to be searched This parameter is mandatory

    • Start looking backwards from this location

    • The default is the length of the array minus 1(arr.length-1), that is, the entire array is searched

    • If the value is greater than or equal to the length of the array, the entire array is searched.

    • If it is negative, it is treated as an offset forward from the end of the array. Even if the value is negative, the array will still be looked up backwards.

    • If the value is negative and its absolute value is greater than the array length, the method returns -1, meaning that the array is not found.

    • Return value: The index of the last occurrence of the element in the array, or -1 if not found.

      var last_array = [2, 5, 9, 2]; var last_array_index = last_array.lastIndexOf(2); last_array_index = last_array.lastIndexOf(7); Last_array_index = last_array.lastIndexof (2, 3); last_array_index = last_array.lastIndexof (2, 3); last_array_index = last_array.lastIndexOf(2, 2); last_array_index = last_array.lastIndexOf(2, -2); last_array_index = last_array.lastIndexOf(2, -1); console.log('last_array_index-------', last_array_index)Copy the code

find

The find() method returns the value of the first element in the array that satisfies the provided test function

Arr. Find (callback[, thisArg])

  • This method takes a callback function that executes on each item of the array and takes three arguments: Element, index, and array

  • Element: The element currently traversed.

  • Index: Indicates the index traversed by the current parameter.

  • Array: the optional parameter array itself

  • ThisArg: Optional argument used as this object for callback

  • The callback function takes three parameters: the value of the current element, the index of the current element, and the array itself

  • // Find the object in the array with its properties

    var inventory = [{ name: 'apples', quantity: 2 },{ name: 'bananas', quantity: 0 },{ name: 'cherries', quantity: 5 }];
    ​let inventory_result = inventory.find(function(fruit, index) {  
       return fruit.name === 'bananas';
    })​
    console.log('inventory_result------', inventory_result)​
    Copy the code

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

The find method does not change the array

findIndex

This method returns the index of the first element in the array that satisfies the provided test function. Returns -1 if no corresponding element is found.

Arr. FindIndex (callback[, thisArg])

  • Element: current element

  • Index: indicates the index of the current element

  • Array: An array to call findIndex

  • Example:

    let findIndex_data = [4, 6, 8, 12].findIndex(function(item, index, array) {

    return item > 5

    })

    console.log(‘findIndex_data—-‘, findIndex_data)

includes

This method is used to determine whether an array contains a specified value, returning true if it does and false otherwise.

Syntax: arr.includes(valueToFind[, fromIndex])

  • ValueToFind: Indicates the value of the element to be searched.

  • FromIndex: This parameter is optional. ValueToFind starts from the fromIndex index. If it is negative, the search starts in ascending order from array.length + fromIndex’s index (even if you skip the fromIndex absolute index from the end and then search backwards). The default is 0.

  • Returns a Boolean, true if it was found in an array (if fromIndex was passed in, it was found in the index range specified by fromIndex).

    • If fromIndex is greater than or equal to the length of the array, false is returned and the array is not searched.

    • If fromIndex is negative, the calculated index is used as the place to start the search for the searchElement. If the calculated index is less than 0, the entire array is searched.

  • Example includes method:

    [1, 2, 3].includes(2);     // true
    [1, 2, 3].includes(4);     // false
    [1, 2, 3].includes(3, 3);  // false
    [1, 2, 3].includes(3, -1); // true
    [1, 2, NaN].includes(NaN); // true
    Copy the code

Returns a Boolean value Boolean

valueOf

This is the default method for array objects, which belong to Object objects. Since all objects “inherit” Object instances, this method can be used by almost all instance objects. Ps: JavaScript Array objects are global objects used to construct arrays, which are higher-order objects similar to lists.

Converts an array to a string and returns the result

The original value representation of an arrayObject.

Grammar: arr. The valueOf ()

var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May'];
months.valueOf();
Copy the code

toString

JavaScript Array objects are global objects used to construct arrays, which are higher-order objects similar to lists. So overrides Object’s toString method

Returns a string representing the specified array and its elements

Grammar: arr. ToString ()

  • Return value: a string representing the specified array and its elements

  • For array objects, the toString method concatenates the array and returns a string containing each array element separated by a comma.

    const array1 = [1, 2, 'a', '1a']; console.log(array1.toString()); / / 1, 2, a, 1 aCopy the code

copyWithin

This method shallowly copies part of the array to another location in the same array and returns it without changing the length of the original array.

Arr. CopyWithin (target[, start[, end]])

entries

The arrayiterator () method returns a new Array Iterator containing key/value pairs for each index in the Array.

Grammar: arr. Entries ()

  • Return value: Returns a new Array iterator object

  • An Array Iterator is an object that has a next method on its prototype

  • The next method can be used to iterate over the iterator to get the [key,value] of the original array.

    var arr_iterator = ["a", "b", "c"];
    var iterator = arr_iterator.entries();
    console.log('iterator-----',iterator.next().value);
    Copy the code

keys

The keys() method returns an Array Iterator containing each index key in the Array

Grammar: arr. Keys ()

  • The example // index iterator contains indexes that have no corresponding element

    const array2_keys = [1, '', 'a', 'b']
    const object_keys = Object.keys(array2_keys);
    console.log('object_keys-------', object_keys)
    var denseKeys = [...object_keys.keys()];
    console.log('denseKeys-------', denseKeys)
    Copy the code
  • Return value: a new Array iterator object.

values

The values() method returns a new Array Iterator containing the value of each index of the Array

Grammar: arr. Values ()

  • Return value: a new Array iterator. This object contains the value of each index of the array

  • Example:

    const array1_values = ['array1_values', 'b', 'c'];
    const iterator_values = array1_values.values();
    console.log('iterator_values', [...iterator_values])
    for (const value of iterator) {
       console.log(value);
    }
    Copy the code

Return value: a new Array iterator.

fill

The fill() method fills all elements of an array from the start index to the end index with a fixed value. Does not include terminating indexes.

Arr. Fill (value[, start[, end]])

  • Value: Mandatory parameter used to fill the value of an array element.

  • Start: The start index is optional. The default value is 0.

  • End: Optional parameter to terminate the index. The default value is this.length.

  • Return value: Modified array.

  • If start is negative, the start index is automatically computed to length+start

  • If end is negative, the end index is automatically evaluated as length+end

  • // If there is only value, start and end have no values

    let data_fill = [1, 2, 3].fill(4); // [4, 4, 4]
    console.log('data_fill------', data_fill)
    Copy the code
  • // If value and start exist

    let data_fill_start = [1, 2, 3].fill(4, 0, 1); // [4, 2, 3]
    console.log('data_fill_start------', data_fill_start)
    Copy the code
  • // Start = array.length + start = 3 + (-3) = 0; Array. length + end = 3 + (-2) = 1

    let fu_fill_start_end = [1, 2, 3].fill(4, -3, -2); // [4, 2, 3]
    console.log('fu_fill_start_end-------', fu_fill_start_end)
    Copy the code

Note: When an object is passed to the fill method, the array is filled with a reference to the object.

reduce

The reduce() method performs a reducer function (in ascending order) that you provide on each element in the array, summarizing its results into a single return value.

Arr. reduce(Callback (Accumulator, currentValue[, index[, array]])[, initialValue])

  • This method receives a callback function that executes the function for each value in the array (except the first value if no initialValue is provided) and contains four arguments:

  • Accumulator: The return value of the accumulator callback; It is the cumulative value, or initialValue, returned when the callback was last called

  • CurrentValue: The element being processed in the array.

  • Index: Index of the current element being processed in the optional parameter array. If initialValue is provided, the starting index is 0, otherwise it starts from index 1.

  • Array: Optional argument to call reduce() array

  • InitialValue: Optional parameter as the value of the first parameter when the callback function is first called.

  • InitialValue: if no initialValue is provided, the first element in the array will be used. Calling reduce on an empty array with no initial value will report an error.

  • If the ARR array is empty and no initialValue is provided, TypeError is raised

  • // The sum of all values in the array

    let reduce_data = [0, 1, 2, 3, 4].reduce(function(accumulator, currentValue, currentIndex, array) { return accumulator + currentValue; }, 4); / / output 14Copy the code
  • // The sum of all values in the array

    var sum = [0, 1, 2, 3].reduce(function (accumulator, currentValue) { return accumulator + currentValue; }, 0); // Input = output 6Copy the code

sort

This method is used to sort the elements of an array

The sorting order can be alphabetic or numeric and in ascending or descending order.

By default, sort() rearranges array elements in ascending order, with the smallest value in front and the largest value behind.

Even if the array’s elements are all numeric, the array is converted to a string and then compared and sorted.

Note: changes the original array, arrays are sorted on the original array, no copies are made

Example: numeric array

let sort_values = [0, 1, 5, 10, 15]; Sort_values.sort (function(a, b) {return a - b})- sort_values.sort(function(a, b) {return b - a}) - sort_values.sort(function(a, b) {return b - a})Copy the code

reverse

This method is also used to sort the elements of an array

Reverse sort, the method is intuitive, but not flexible enough

Note: changes the original array, arrays are sorted on the original array, no copies are made

Example: numeric array

let reverse_values = [0, 1, 5, 10, 15];
reverse_values.reverse()
console.log('sort_values-------', reverse_values)
Copy the code

slice

This method can take one or two arguments: return the starting and ending index of the element.

If there is only one argument, slice() returns all elements of the index to the end of the array.

If there are two arguments, slice() returns all elements from the start index to the end index, with no elements from the end index.

slice(start,end)

  • Start a necessity. Specify where to start. If it is negative, it specifies the position from the end of the array.

    • That is, -1 is the last element, -2 is the next-to-last element, and so on.
  • The end is optional. Specify where to end the selection. This parameter is the array subscript at the end of the array fragment.

Example: let colors = [“red”, “green”, “blue”, “yellow”, “purple”];

  • If there is only one argument, slice() returns all elements of the index to the end of the array.

  •   // let colors2 = colors.slice(1);
      // console.log('colors---------', colors2)
      let colors3 = colors.slice(-1)
      console.log('colors3---------', colors3)
    Copy the code
  • If there are two arguments, slice() returns all elements from the start index to the end index, with no elements from the end index.

  • let colors3 = colors.slice(1, 4); console.log('colors3---------', colors3); Print: ["green", "blue", "yellow"]Copy the code

The slice() method does not alter the original array.

  • The console. The log (‘ colors — — — — — — — — — slice () method will not change the original array ‘, colors) / / [” red “, “green”, “blue”, “yellow”, “purple”]

splice

The add or remove method is used to add or remove elements from an array.

let splice_colors = [‘red’, ‘green’, ‘blue’]

The main purpose is to insert elements in the middle of an array, but there are three different ways to use this method.

  • The first method removes functionality

  • You need to pass splice() two arguments

    • The first is the location of the element to delete, and the second is the number of elements to delete.

    • You can remove any number of elements from an array, such as splice(0, 2), which removes the first two elements.

    • Let removed_delete = splice_colors. Splice (0, 1); // Delete function

  • The second way is to insert functionality

  • You need to pass splice() three arguments

    • The first element is the starting position, the second number of elements to delete, and the third element to insert (as many elements as you can insert)

    • You can insert elements at specified positions in the array. The third argument can be followed by a fourth argument, a fifth argument, or any number of elements to be inserted.

    • For example, splice(2, 0, “red”, “green”) inserts the strings “red” and “green” from array position 2.

    • splice_colors.splice(1, 0, “yellow”, “orange”); // Insert function

  • The third way is to replace functionality

  • Again, you pass in three arguments

    • The first element is the starting position, the second number of elements to delete, and the third element to insert (as many elements as you can insert)

    • The number of elements to be inserted is not necessarily the same as the number of elements to be deleted

    • For example, splice(2, 1, “red”, “green”) removes an element at position 2 and inserts “red” and “green” into the array starting at that position.

    • splice_colors.splice(1, 2, “red”, “purple”); // Insert two values and delete two elements

Note: This method alters the original array.

pop

This method is used to delete the last item of the array and reduce the length value of the array to return the deleted item

unshift

let pop_arr = [1, 4, 5, 7, 3]​ 
let item_pop = pop_arr.pop();
console.log('item_pop', item_pop) // 3​
Copy the code

This method adds any number of values to the beginning of the array and returns the new array length

let unshift_arr = new Array(); Let unshift_item = unshift_arr. Unshift,2,34 (1) the console. The log (' unshift_arr -- -- -- -- -- -- -- -- -- ', Unshift_arr) / / 1,2,34 console. The log (' unshift_item length -- -- -- -- -- -- -- -- -- ', unshift_item) / / 3Copy the code

shift

This method deletes the first item of the array and returns the item it deleted

let shift_arr = [1, 4, 5, 7, 3]; let shift_item = shift_arr.shift(); The console. The log (' shift_arr -- -- -- -- -- -- -- -- ', shift_arr) / / 4,57,3 console. The log (' shift_item -- -- -- -- -- -- -- -- -- ', shift_item) / / 1Copy the code

push

This method takes any number of arguments and adds them to the end of the array, returning the latest length of the array

let push_arr = [1, 4, 5, 7, 3] let push_item = push_arr.push({demo:123}) console.log('push_item--------', Push_item) / / array length is 6 the console. The log (' push_arr -- -- -- -- -- -- -- -- ', push_arr)Copy the code