Create an array

let a = [5.6.7] // the literal way
let a = new Array(a)// constructor
let a = Array(a)// You can omit new

// Note that taking a number as an argument creates an empty array of length 2
let a = Array(2)
console.log(a) / / / the empty x 2
Copy the code

A static method

Array.of() converts the argument to an Array instance

Creates a new array instance with a variable number of arguments, regardless of the number or type of arguments.

Commonly used Array. Before this method is used to replace ES6 prototype. Slice. The call (the arguments) converts the arguments object to an Array of writing.

conconsole.log(Array.of(5)) / / [5]
console.log(Array.of("hello".5.function foo() {}))/ / [" hello ", 5, ƒ]
Copy the code

Array.from() converts a class Array structure into an Array instance

Creates a new, shallow-copy array instance from an array of classes (an iterable or any object with a length and indexable property).

  • arraylikeA pseudo-array object or iterable that you want to convert to an array.
  • mapFnIf specified, each element in the new array executes the callback function.
  • thisArgOptional argument to execute the callback functionmapFnthisObject.
// Generate an array from String
console.log(Array.from('foobar')) // ["f", "o", "o", "b", "a", "r"]

// Generate an array from Set
const set = new Set(['foo'.'bar'.'baz'.'foo'])
console.log(Array.from(set))// ["f", "o", "o", "b", "a", "r"]

// Generate an array from Map
const map = new Map([[1.2], [2.4], [4.8]])
console.log(Array.from(map)) // [[1, 2], [2, 4], [4, 8]]
console.log(Array.from(map.keys())) / / [1, 2, 4]
console.log(Array.from(map.values())) / / (2, 4, 8]

// Generate arrays from class array objects (arguments)
function f() {
    return Array.from(arguments)}console.log(f(1.'foo'[6.7])) // [1, "foo", [6, 7]]
Copy the code

Instance methods

Modifier method (changing the original array)

Pop () removes the last item in the array

Removes the last element from the array and returns the value of that element.

const colors = ['red'.'green'.'blue'.'orange']
console.log(colors.pop()) // orange
console.log(colors) // ["red", "green", "blue"]

const arr = []
console.log(arr.pop()) // undefined
Copy the code

Push () inserts elements at the end of the array

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

const colors = ['red'.'green']
console.log(colors.push('blue'.'orange')) / / 4
console.log(colors) // ["red", "green", "blue", "orange"]
Copy the code

Unshift () inserts elements at the beginning of the array

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

const arr = [1.2.3.4.5]
console.log(arr.unshift(6.7))
console.log(arr) // [6, 7, 1, 2, 3, 4, 5]
Copy the code

Shift () removes the first element of the array

Removes the first element from the array and returns the value of that element.

const arr = [1.2.3.4.5]
console.log(arr.shift()) / / 1
const arr2 = []
console.log(arr2.shift()) // undefined
Copy the code

Splice () adds/removes array elements

Modify an array by deleting or replacing existing elements or adding new ones in place, and return the modified contents as an array.

  • startSpecifies the starting position of the modification (counting from 0).
    • Positive, overarray.length, adding from the end of the array;
    • A negative number, the number of digits starting from the bottom of the array (equivalent toarray.length-n);
    • Negative, the absolute value is greater than the array length, indicating that the starting position is bit 0.
  • deleteCount optionalAn integer representing the number of array elements to remove.
    • deleteCountGreater than or equal tostartThe total number of subsequent elements (array.length-start), then fromstartAll subsequent elements will be deleted (including the firststartA);
    • deleteCountIt’s left out, sostartThen all the elements of the array are removed;
    • deleteCountIf it’s 0 or negative, it doesn’t remove the element. In this case, at least one new element should be added.
  • item1, item2, ... optionalThe element to be added to the array fromstartPosition start. If this parameter is not specifiedsplice()Only array elements will be removed.
/ / delete
let colors = ['red'.'green'.'blue'.'brown'.'orange']
let removed = colors.splice(1.1)
console.log(colors) // ["red", "blue", "brown", "orange"]

let colors1 = ['red'.'green'.'blue'.'brown'.'orange']
let removed1 = colors1.splice(0.8)
console.log(colors1) // [] deleteCount is greater than start, all elements are deleted

let colors2 = ['red'.'green'.'blue'.'brown'.'orange']
let removed2 = colors2.splice(0.5)
console.log(colors2) // [] deleteCount = start, all elements are deleted

let colors3 = ['red'.'green'.'blue'.'brown'.'orange']
let removed3 = colors3.splice(0)
console.log(colors3) // [] omit deleteCount, all elements are deleted

/ / insert
let colors = ['red']
let insert = colors.splice(0.0.'green'.'blue')
console.log(colors) // ["green", "blue", "red"]

let colors1 = ['red']
let insert1 = colors1.splice(5.0.'green'.'blue')
console.log(colors1) // ["red", "green", "blue"] start > array.length

let colors2 = ['red'.'green'.'blue']
let insert2 = colors2.splice(-2.0.'brown'.'orange')
console.log(colors2) // ["red", "brown", "orange", "green", "blue"] start negative numbers start from the last number of start (-1)

let colors3 = ['red']
let insert3 = colors3.splice(-5.0.'yellow'.'brown')
console.log(colors3) // ["yellow", "brown", "red"] start Negative absolute value greater than the array length, starting from 0

/ / replace
let colors = ['red']
let replace = colors.splice(0.1.'green'.'blue')
console.log(colors) // ["green", "blue"] delete 1 item, insert 2 item

let colors1 = ['red'.'green'.'blue']
let replace1 = colors1.splice(0.2.'orange')
console.log(colors1) // ["orange", "blue"] delete 2 items, insert 1 item
Copy the code

Sort () sorts array elements

Sort the elements of an array using the in place algorithm and return the array. The default sort order is built when converting elements to strings and then comparing their UTF-16 code unit value sequences.

  • compareFunction optionalUsed to specify functions that are sorted in a certain order. If omitted, the element follows each character of the converted stringUnicodeThe locus is sorted.
    • FirstEl is the first element used for comparison.
    • SecondEl The second element used for comparison.

If compareFunction is specified, the array is sorted by the value returned from calling the function. Suppose a and B are the two elements to be compared:

  • ifcompareFunction(a, b)Less than 0, so a is going to be placed before B.
  • ifcompareFunction(a, b)Is equal to 0, the relative positions of a and b remain the same.
  • ifcompareFunction(a, b)Greater than 0, b will be placed before A.
  • compareFunction(a, b)The same comparison must always be returned for the same input, or the sorting result will be indeterminate.
// Compare string functions
function compare(a, b) {
    if (a < b) {
        return -1
    }
    if (a > b) {
        return 1
    }
    return 0
}
// Compare numeric functions
function compareNumbers(a, b) {
    return a - b 
}
Copy the code
// The comparison function is not specified
let num = [1.5.37.80.9]
console.log(num.sort()) // [1, 37, 5, 80, 9] According to Unicode, 35 precedes 5 and 80 precedes 9

// The comparison function is specified
let num = [1.5.37.80.9]
console.log(num.sort()) // [1, 37, 5, 80, 9]
console.log(num.sort((a, b) = > a - b)) // [1, 5, 9, 37, 80
Copy the code

Reverse () reverses the position of an array element

Reverses the position of the elements in an array and returns the array.

let arr = ['one'.'two'.'three']
console.log('arr:', arr) // ["one", "two", "three"]
let reversed = arr.reverse()
console.log('reverse:', reversed) // ["three", "two", "one"]
console.log('arr:', arr) // ["three", "two", "one"]
Copy the code

CopyWithin () copies part of the array to another location (ES6)

Shallow copies part of the array to another location in the same array and returns it.

  • target0 is the base index, and the sequence is copied to that position.
    • If it’s a negative number,targetWill calculate from the end.
    • iftargetGreater than or equal toarr.length, no copy will occur.
    • iftargetstartAfter that, the copied sequence is modified to fitarr.length.
  • start0 is the base index at which the copy element starts.
    • If it’s a negative number,startWill calculate from the end.
    • ifstartBe ignored,copyWithinWill copy from 0.
  • end0 is the index of the base and the end position of the start copy element.
    • copyWithinWill be copied to the location, but not includedendThe element at this position.
    • If it’s a negative number,endWill calculate from the end.
    • ifendBe ignored,copyWithinMethods are copied to the end of the array (defaultarr.length).
// target
let arr = ['a'.'b'.'c'.'d'.'e']
console.log(arr.copyWithin(0.3.4)) // ["d", "b", "c", "d", "e"] Normal copy does not include end element
let arr2 = ['a'.'b'.'c'.'d'.'e']
console.log(arr2.copyWithin(6.3.4)) / / [" a ", "b", "c", "d", "e"] target is greater than the arr. The length is not copy
let arr3 = ['a'.'b'.'c'.'d'.'e']
console.log(arr3.copyWithin(4.3.4)) / / [" a ", "b", "c", "d", "d"] target is greater than the start neglected before the start of elements
// start
let arr = ['a'.'b'.'c'.'d'.'e']
console.log(arr.copyWithin(0, -3.4)) / / / "c", "d", "c", "d", "e"] start from the end - 3 c
let arr2 = ['a'.'b'.'c'.'d'.'e']
console.log(arr2.copyWithin(2)) / / / "a", "b", "a", "b", "c"] start are ignored, copywithin starting from 0 replication
// end
let arr = ['a'.'b'.'c'.'d'.'e']
console.log(arr.copyWithin(2.3.4)) / / / "a", "b", "d", "d", "e"] end does not include this element target c copy for d
let arr2 = ['a'.'b'.'c'.'d'.'e']
console.log(arr2.copyWithin(2.0, -4)) / / / "a", "b", "a", "d", "e") from the end of the end - 4, c copy as a
let arr3 = ['a'.'b'.'c'.'d'.'e']
console.log(arr3.copyWithin(2.3)) // ["a", "b", "d", "e", "e"] end is ignored until end target c copies start d to end e
Copy the code

Fill () fills the array with fixed values (ES6)

  • Value is used to fill in the value of an array element.
  • start optionalStart index. Default value is 0.
  • end optionalTerminates the index. The default value isthis.length.
let arr = [1.2.3.4.5]
console.log(arr.fill(6)) // [6, 6, 6, 6, 6]
let arr2 = [1.2.3.4.5]
console.log(arr2.fill(7.1.3)) // [1, 7, 7, 4, 5] 7 fills elements 1-3
let arr3 = [1.2.3.4.5]
console.log(arr3.fill(8.3)) // [1, 2, 3, 8, 8] 8 fills the element greater than 3
let arr4 = [1.2.3.4.5]
console.log(arr4.fill(9, -4, -1)) // [1, 9, 9, 9, 5] 9 Fills the length+start to length+end element
let arr5 = [1.2.3.4.5]
console.log(arr5.fill(8.3)) // [1, 2, 3, 8, 8] 8 fills the element greater than 3
let arr6 = [1.2.3.4.5]
console.log(arr6.fill(6.3.10)) // [1, 2, 3, 6, 6] 6 Fill the available parts
Copy the code

Accessor methods (without changing the original array)

ToString () array toString

Returns a string representing the specified array and its elements.

let colors = ["red"."blue"."green"]
console.log(colors.toString()) // red,blue,green
Copy the code

ToLocaleString () array to string

Returns a string representing the elements in the array. The elements in the array are converted to strings using their respective toLocaleString methods, which are separated by a locale-specific string (such as a comma “,”).

  • locales optionalString or array of strings with BCP 47 language markup, aboutlocalesFor the form and explanation of parameters, seeIntlPage.
  • options optionalAn object with configurable properties for numbersNumber.prototype.toLocaleString(), for datesDate.prototype.toLocaleString().
let arr = [1."a".new Date('21 Dec 1997 9:13:00 UTC')]
const localeString = arr.toLocaleString('en', { timeZone: 'UTC' })
console.log(localeString) // 1,a,12/21/1997, 9:13:00 AM
Copy the code

Join () array to string

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

  • separator optionalSpecifies a string to delimit each element of the array. Convert the delimiter to a string if necessary. If it defaults to this value, array elements are comma (.). ifseparatorIs an empty string (""), there are no characters between all elements.
let colors = ['red'.'green'.undefined.null.'blue']
console.log(colors.join()) // red,green,, blue undefined null converts to an empty string
console.log(colors.join(The '-')) // red-green---blue
console.log(colors.join('+')) // red+green+++blue
Copy the code

If an element is undefined or null, it is converted to an empty string.

Concat () merges arrays

Used to merge two or more arrays.

  • value NoptionalArrays and/or values will be merged into a new array. If I omit all of themvalueNParameter,concatReturns a shallow copy of the existing array that called the method.
let num1 = [[1]]
let num2 = [2[3]]
let num3 = [5[6]]
let nums = num1.concat(num2, num3)
console.log(nums) // [1, 2, 3, 4, 5, 6, 7, 8, 9]

// Merge nested arrays
let num1 = [[1]]
let num2 = [2[3]]
let num3 = [5[6]]
let nums = num1.concat(num2, num3)
console.log(nums) / / [[1], 2 [3], 5, [6]]
Copy the code

Slice () shallowly copies the original array elements

Returns a new array object that is a shallow copy of the array determined by begin and end (begin, but not end).

  • begin optionalExtract the index at the start (from0Start), extracting the original array elements from the index.
    • If this parameter is negative, it indicates the number of elements from the penultimate of the original array to be extracted.slice(-2)Extract the penultimate element of the array to the last element (including the last element).
    • If you omitbegin,sliceFrom the index0Start.
    • ifbeginBeyond the index range of the original array, an empty array is returned.
  • end optionalExtracts the index at the termination (from0Start), ends at the index to extract the original array element.
    • sliceWill extract the original array index frombeginendAll elements of thebegin, but does not containend).
    • If this parameter is negative, it indicates the penultimate element in the original array at the end of the extraction.
    • ifendIs omitted, thensliceIt will fetch all the way to the end of the original array.
    • ifendGreater than the length of the array,sliceIt will also fetch all the way to the end of the original array.
let fruits = ['Banana'.'Orange'.'Lemon'.'Apple'.'Mango']
let citrus = fruits.slice(1.3)
console.log(citrus) // ["Orange", "Lemon"]

// Class array object
function list() {
    return Array.prototype.slice.call(arguments)}let list1 = list(1.2.3)
console.log(list1) / / [1, 2, 3]
Copy the code

IndexOf () returns the first indexOf the specified element

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

  • SearchElement The element to find.
  • fromIndex optionalThe location to 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.
    • If the offset index is still less than 0, the entire array will be queried.

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.

let colors = [1.2.3.4.5.6.7.8.9]
console.log(colors.indexOf(5)) / / 4
console.log(colors.indexOf(5.10)) // If -1 is greater than or equal to the array length, return -1
console.log(colors.indexOf(5, -1)) // -1 returns -1 by looking backwards from 9
console.log(colors.indexOf(5, -6)) // 4 returns 4 by looking backwards from 4
console.log(colors.indexOf(5, -10)) // 4 if the index is less than 0, search the entire array and return 4
Copy the code

LastIndexOf () returns the lastIndexOf the specified element

Returns the index of the last element in the array for the specified element (that is, a valid JavaScript value or variable), or -1 if none exists. Look forward from the back of the array, starting at fromIndex.

  • SearchElement The element to be searched.
  • fromIndex optionalStart looking backwards from this location. Default is the array length 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 it is negative and its absolute value is greater than the length of the array, the method returns -1, meaning the array will not be looked up.
let colors = [1.2.3.4.5.6.7.8.9]
console.log(colors.lastIndexOf(1)) // 0 By default, the entire array is searched
console.log(colors.lastIndexOf(9.9)) // 8 fromIndex is greater than or equal to the length of the array. The entire array is searched
console.log(colors.lastIndexOf(5, -5)) // 4 fromIndex is negative, offset from the end of the array forward
console.log(colors.lastIndexOf(5, -6)) // the search starts at 4. Since the search starts from back to front, return -1
console.log(colors.lastIndexOf(5, -10)) If the absolute value of fromIndex is greater than the array length, the method returns -1
Copy the code

Whether the includes() array contains the specified value (ES7)

Used to determine whether an array contains a specified value, returning true if it does, false otherwise.

  • ValueToFind Specifies the element value to be searched.
  • fromIndex optionalfromIndexThe search begins at the indexvalueToFind.
    • If it is negative, the value is in ascending order fromarray.length + fromIndexIndex began to search.

Note: Using includes() to compare strings and characters is case sensitive.

let numbers = [1.2.3.4.5.6.7.8.9]
console.log(numbers.includes(5)) // true
console.log(numbers.includes(5.6)) // false fromIndex greater than valueToFind index value
console.log(numbers.includes(5.10)) // false fromIndex is greater than or equal to the array length
console.log(numbers.includes(5, -5)) // true array.length + fromIndex = 4
console.log(numbers.includes(8, -1)) // false searches from index 8
console.log(numbers.includes(5, -10)) // true If the calculated index is less than 0, the entire array is searched.
Copy the code

An iterative approach

ForEach () performs the given function once on each element of the array

The callback function is executed once for each item in the array that has a valid value, in ascending order, and those items that have been deleted (using the delete method, etc.) or have not been initialized are skipped (for example, on a sparse array, undefined is not included).

  • callbackA function executed for each element in the array that takes one to three arguments:
    • The current element being processed in the currentValue array.
    • index optionalThe index of the current element being processed in the array.
    • array optional forEach()Method is operating on an array.
  • thisArg optionalWhen the callback function is executedcallbackWhen used asthisThe value of the.
    • ifthisArgIf the parameter has a value, then each timecallbackWhen the function is called,thisLeads tothisArgParameters.
    • If you omitthisArgArgument, or its value isnullundefined.thisPoints to a global object.

Note:

  1. The scope of forEach() traversal is determined before the first callback is called.

    Items added to the array after a call to forEach are not accessed by the callback.

    If an existing value is changed, the value passed to the callback is the value that forEach() traversed up to their moment.

    If the accessed element is removed during iteration (for example, using Shift ()), then the element is skipped.

  2. ForEach () performs a callback forEach array element; It always returns undefined (that is, no return value) and cannot be called chained.

  3. When forEach() is called, it does not directly change the object on which it was called, but that object may be changed by callback.

    • The value type is not changed, the reference type is changed.
  4. There is no way to abort or break out of the forEach() loop except by throwing an exception.

// Do nothing to uninitialized values (sparse array)
let nums = [1.3.7]
let numCallbackRuns = 0
nums.forEach(function (element) {
    console.log(element)
    numCallbackRuns++
})
console.log('numCallbackRuns:', numCallbackRuns) // 1 3 7 numCallbackRuns: 3

/ / use thisArgs
function Counter() {
    this.sum = 0
    this.count = 0
}
Counter.prototype.add = function (array) {
    array.forEach(function (entry) {
        this.sum += entry
        ++this.count
    }, this)
    // Because thisArg argument (this) is passed to forEach(), it is passed to the callback function every time it is called as its this value.
}

const obj = new Counter()
obj.add([2.5.9])
// 3 === (1 + 1 + 1)
obj.sum
// 16 === (2 + 5 + 9) 

// Pass the function with the arrow function expression. ThisArgs arguments are ignored
let nums2 = [1.2.3]
nums2.forEach((v, i, arr) = > {
    console.log(this) // window window window
})

// If the array is modified during iteration, other elements are skipped
let words = ['one'.'two'.'three'.'four']
words.forEach((word) = > {
    console.log(word)
    if (word === 'two') {
        words.shift()
    }
}) // one two four

// No return value
let nums3 = [1.2.3.4.5]
let value = nums3.forEach((v, i, arr) = >{})console.log(value) // undefined

// Chained calls are not supported
[1.2.3.4.5].forEach(item= > {
    console.log(item)
}).filter(item= > {
    return item > 2 // Uncaught TypeError: Cannot read property 'filter' of undefined
})


// when forEach() is called, the object calling it is changed by the callback function
let nums4 = [1.2.3.4.5]
nums4.forEach((v, i, arr) = > {
    arr[i] = v * 2
})
console.log(nums4) // [2, 4, 6, 8, 10] change

nums4.forEach(item= > {
    item = item * 2
})
console.log(nums4) // [2, 4, 6, 8, 10] no change

// There is no way to abort or break out of the forEach() loop except by throwing an exception
let nums5 = [1.2.3.4.5]
// nums5.forEach((v, i, arr) => {
// console.log(v)
// if (i === 2) {
// break // Uncaught SyntaxError: Illegal break statement
/ /}
// })

nums5.forEach((v, i, arr) = > {
    console.log(v)
    if (v === 2) {
        console.log(Awesome!)
        return false // 1 2 666 3 4 5}})Copy the code

Map () performs the passed function on each item of the array, returning the new array

The callback function is called once for each element in the array, in order. The return values (including undefined) from each callback are combined to form a new array.

Callback is called only on indexes that have values; Indexes that have never been assigned a value or deleted with delete are not called.

  • callbackA function that generates a new array element, taking three arguments:
    • currentValue callbackThe current element in the array being processed.
    • indexoptional callbackThe index of the current element being processed in the array.
    • arrayoptional mapAn array of method calls.
  • thisArgoptionalperformcallbackFunction time values are used asthis.
  1. A map generates a new array. Using a map when you do not intend to use the returned array is not intended. Use forEach or for-of instead.

    When you should not use map:

    • You are not going to use the new array returned;
    • You did not return a value from the callback function.
  2. If thisArg is supplied to map, it will be used as the this value of the callback. Otherwise, undefined will be used as this for the callback function.

  3. Map does not modify the array itself that calls it (although it can change the array when callback is executed).

  4. The extent to which the map method handles array elements is determined before the callback method is called for the first time.

    The array elements appended after the map method is called are not accessed by the callback.

    If an existing array element changes, the value passed to the callback is the value at which the map accessed the element.

    The element cannot be accessed if it is deleted after the map function is called but before it is accessed.

  5. According to the algorithm defined in the specification, if the array called by map is discrete, the new array will also be discrete, leaving the same index empty.

// Map returns the new array unchanged (can be changed by callback)
let nums = [1.4.9]
let roots = nums.map(Math.sqrt)
console.log(roots, nums) // [1, 2, 3] [1, 4, 9]

// The return value of undefined will be combined into a new array
let newArr = [1.2.3.4.5].map(item= > {
    if (item > 3) {
        return item
    }
})
console.log(newArr) // [undefined, undefined, undefined, 4, 5]

// Use map to reformat the objects in the array
let kvArray = [{ key: 1.value: 10 }, { key: 2.value: 20 }, { key: 3.value: 30 }]
let refmArray = kvArray.map(function (obj) {
    let rObj = {}
    rObj[obj.key] = obj.value
    return rObj
})
console.log(refmArray, kvArray) // [{1:10},{2:20},{3:30}] [{ key: 1, value: 10 }, { key: 2, value: 20 }, { key: 3, value: 30 }]

// Use a function that takes one parameter to map an array of numbers
let nums2 = [1.4.9]
let doubles = nums2.map(function (num) {
    return num * 2
})
console.log(doubles, nums2) // [2, 8, 18] [1, 4, 9]

/ / querySelectorAll application
let elems = document.querySelectorAll('select option:checked')
let values = Array.prototype.map.call(elems, function (obj) {
    return obj.value
})
console.log(values) // [] We get all the selected options in the document and print them
Copy the code

Tips case

console.log(['1'.'2'.'3'].map(parseInt)) // [1, NaN, NaN]
Copy the code

This result occurs because parseInt takes two arguments:

  • The first argument is an expression that represents the value to be parsed.
  • The second argument is a number that represents the cardinality of the string.

The third map argument, the array itself, is ignored by parseInt, and the index passed by the second argument is used as a base number, so NaN is returned.

The solution

// Returns a base 10 integer
function returnInt(element) {
    return parseInt(element, 10)}console.log(['1'.'2'.'3'].map(returnInt)) / / [1, 2, 3]

// Use the arrow function
console.log(['1'.'2'.'3'].map(str= > parseInt(str))) / / [1, 2, 3]

// Convert the string using Number
console.log(['1'.'2'.'3'].map(Number)) / / [1, 2, 3]
Copy the code

Filter () filters the original function and returns a new array

Call callback once for each element in the array and create a new array with all elements that cause callback to return true or its equivalent.

  • callbackA function that tests each element of an array. returntrueIndicates that the element passes the test, the element is retained,falseIs not reserved. It takes the following three parameters:
    • Element The element in the array that is currently being processed.
    • indexoptionalThe index of the element being processed in the array.
    • arrayoptionalCall thefilterThe array itself.
  • thisArgoptionalperformcallbackWhen used inthisThe value of the.
  1. Callback will only be called on indexes that have been assigned, not indexes that have been deleted or never assigned.

    Elements that do not pass the callback test are skipped and not included in the new array.

  2. If a thisArg argument is provided to filter, it will be used as this when callback is called.

    Otherwise, callback’s this value will be global in non-strict mode and undefined in strict mode.

  3. Filter does not alter the original array; it returns the filtered new array.

  4. The range of elements traversed by filter is determined before the first callback is called.

    Elements added to the array after a call to filter are not traversed by filter.

    If existing elements are changed, the value they pass to the callback is the value filter traverses up to that point in time.

    Elements that are deleted or never assigned are not traversed.

const words = ['HTML'.'CSS'.'JavaScript'.'Java'.'Vue'.'React']
const result = words.filter(word= > word.length > 6)
console.log(result) // ["JavaScript"]
Copy the code

Is there any element in the some() array that meets the criteria

Each element in the array executes the callback function once until a value is found that causes the callback to return a “true” value (which can be converted to a Boolean value of true).

If such a value is found, some() will immediately return true. Otherwise, some() returns false.

Callback will only be called on “valued” indexes, not indexes that have been deleted or never assigned a value.

  • callbackThe function used to test each element, taking three arguments:
    • Element The element being processed in the array.
    • index optionalThe index value of the element being processed in the array.
    • arrayoptional some()The array to be called.
  • thisArgoptionalperformcallbackThe use ofthisValue.
  1. If a thisArg argument is supplied to some(), it will be used as the this value of the callback being called. Otherwise, its this value will be undefined.

  2. Some () is called without changing the array.

  3. The scope of the elements traversed by some() is determined before the first callback is called.

    The value added to the array after calling some() is not accessed by the callback.

    If an element in the array that has not yet been accessed is changed by the callback, the value passed to the callback is the value at which some() accessed it.

    Deleted elements will not be accessed.

// Tests the value of an array element
function isBiggerThan10(element, index, array) {
    return element > 10
}

console.log([2.5.8.9.1].some(isBiggerThan10)) // false
console.log([12.5.8.9.1].some(isBiggerThan10)) // true

// Use the arrow function to test the value of an array element
console.log([1.5.6.9].some(x= > x > 10)) // false
console.log([12.5.1.9].some(x= > x > 10)) // true

// Determine whether a value exists in an array element
let fruits = ['apple'.'banana'.'mango'.'guava']

function checkAvailability(arr, val) {
    return arr.some(function (arrVal) {
        return val === arrVal
    })
}
console.log(checkAvailability(fruits, 'kela')) // false
console.log(checkAvailability(fruits, 'banana')) // true

// Convert any value to a Boolean type
let TRUTHY_VALUES = [true.'true'.1]
function getBoolean(value) {
    'use strict'
    if (typeof value === 'string') {
        value = value.toLowerCase().trim()
    }
    return TRUTHY_VALUES.some(function (t) {
        return t === value
    })
}

console.log(getBoolean(false)) // false
console.log(getBoolean('false')) // false
console.log(getBoolean(1)) // true
console.log(getBoolean('true')) // true
Copy the code

Whether all elements in the every() array satisfy the condition

Callback is executed once for each element in the array until it finds an element that causes callback to return Falsy.

If one is found, the every method will immediately return false. Otherwise, callback returns true for each element, and every returns true.

Callback will only be called for indexes that have already been assigned a value. Not called for indexes that are deleted or never assigned.

  • callbackThe function used to test each element, which can take three arguments:
    • Element is the current value used for testing.
    • indexoptionalThe index of the current value used for testing.
    • arrayoptionalcalleveryThe current array of.
  • thisArgperformcallbackThe use ofthisValue.
  1. If a thisArg argument is provided for every, it is the this value when callback is called.

    If omitted, the value of this when callback is called is global in non-strict mode, and undefined in strict mode.

  2. Every does not change the array.

  3. The scope of every traversal is determined before the first callback is called.

    Elements added to the array after every are called are not accessed by the callback.

    If an element in the array is changed, they pass the value every at the moment they are accessed to the callback.

    Elements that are deleted or that have never been assigned a value will not be accessed.

  4. Every, like the word “all” in mathematics, returns true when all elements meet the criteria. Because of this, passing an empty array returns true anyway.

// Check the size of all array elements
function isBigEnough(element, index, array) {
    return element >= 10
}

console.log([12.5.8.130.44].every(isBigEnough)) // false
console.log([12.54.18.130.44].every(isBigEnough)) // true

// Arrow function
console.log([12.5.8.130.44].every(x= > x >= 10)) // false
console.log([12.54.18.130.44].every(x= > x >= 10)) // true
Copy the code

Reduce () provides an accumulator for an array, summed up into a single value

Callback is executed for each element in the array, excluding elements that were deleted or never assigned.

  • Callback executes the function for each value in the array (except the first value if no initialValue is provided) and contains four arguments:

    • accumulatorThe return value of the accumulative callback; It is the cumulative value returned when the callback was last called, orinitialValue(See below).
    • currentValueThe element in the array being processed.
    • index optionalThe index of the current element being processed in the array. If providedinitialValue, the start index is 0; otherwise, the start index is 1.
    • arrayoptionalcallreduce()The array.
  • InitialValue Is optional as the value of the first argument when the callback function is first called.

    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.

  1. Accumulator and currentValue are two different values when the callback function is first executed:

    If initialValue is provided when reduce() is called, accumulator is initialValue and currentValue is the first value in the array.

    If no initialValue is provided, accumulator takes the first value in the array and currentValue takes the second value in the array.

  2. If the array is empty and no initialValue is provided, TypeError is raised.

    If the array has only one element (regardless of position) and no initialValue is provided, or if initialValue is provided but the array is empty, this unique value will be returned and the callback will not be executed.

Note: If no initialValue is provided, Reduce executes the callback method starting at index 1, skipping the first index. If initialValue is provided, start at index 0.

It is usually safer to provide an initialValue, as in the following example, if initialValue is not provided, there may be four outputs:

let maxCallback = (acc, cur) = > Math.max(acc.x, cur.x)
let maxCallback2 = (max, cur) = > Math.max(max, cur)

// reduce() has no initial value
console.log([{ x: 2 }, { x: 22 }, { x: 42 }].reduce(maxCallback)) // NaN 
console.log([{ x: 2 }, { x: 22 }].reduce(maxCallback))  {x:2}} {x:2}} {x:2}} {x:2}}
console.log([{ x: 2 }].reduce(maxCallback)) The {x: 2} array uses only one element, this unique value will be returned and callback will not be executed
console.log([].reduce(maxCallback)) //Uncaught TypeError: Reduce of Empty array with no Initial Value The array is empty and no initialValue is provided

// Map /reduce This is a better solution, passing an empty array or a larger array will work fine
console.log([{ x: 22 }, { x: 42 }].map(el= > el.x).reduce(maxCallback2, -Infinity)) / / 42
Copy the code

Why did the first one print NaN?

  1. No initialValue is provided. The Accumulator is {x:2} and currentValue is the second value in the array {x:22}.

    Equivalent to [{x: 22}, {x: 42}].reduce(maxCallback, {x: 2}).

  2. The first operation is {x:2} and {x:22} and the result is 22.

  3. The second operation is 22 and {x:42}, (22). X is undefined, so math.max (undefined,42) is NaN.

So it’s better to try map first and get all the x’s out.

How does reduce() work

If we run the next reduce() code:

[0.1.2.3.4].reduce(function (accumulator, currentValue, currentIndex, array) {
    return accumulator + currentValue
})

// Use the arrow function
[0.1.2.3.4].reduce((prev, curr) = > prev + curr)
Copy the code

Callback is called four times, and the parameters and return values of each call are as follows:

callback accumulator currentValue currentIndex array return value
first call 0 1 1 [0, 1, 2, 3, 4] 1
second call 1 2 2 [0, 1, 2, 3, 4] 3
third call 3 3 3 [0, 1, 2, 3, 4] 6
fourth call 6 4 4 [0, 1, 2, 3, 4] 10

The value returned by reduce will be the last callback return value (10).

If you want to provide an initial value as the second argument to the reduce() method, here’s how it works and what happens:

[0.1.2.3.4].reduce((accumulator, currentValue, currentIndex, array) = > {
    return accumulator + currentValue
}, 10)
Copy the code
callback accumulator currentValue currentIndex array return value
first call 10 0 0 [0, 1, 2, 3, 4] 10
second call 10 1 1 [0, 1, 2, 3, 4] 11
third call 11 2 2 [0, 1, 2, 3, 4] 13
fourth call 13 3 3 [0, 1, 2, 3, 4] 16
fifth call 16 4 4 [0, 1, 2, 3, 4] 20

In this case reduce() returns a value of 20.

// The sum of all values in the array
let sum = [0.1.2.3].reduce(function (accumulator, currentValue) {
    return accumulator + currentValue
}, 0)
console.log(sum) / / 6

// Convert a two-dimensional array to a one-dimensional array
let flattened = [[0.1], [2.3], [4.5]].reduce(
    function (a, b) {
        return a.concat(b)
    }, []
)
console.log(flattened) // [0, 1, 2, 3, 4, 5]

// Count the number of occurrences of each element in the array
let names = ['Alice'.'Bob'.'Tiff'.'Bruce'.'Alice']
let countedNames = names.reduce(function (allNames, name) {
    if (name in allNames) {
        allNames[name]++
    } else {
        allNames[name] = 1
    }
    return allNames
}, {})
console.log(countedNames) // {Alice: 2, Bob: 1, Tiff: 1, Bruce: 1}

// Classify objects by attribute
var people = [
    { name: 'Alice'.age: 21 },
    { name: 'Max'.age: 20 },
    { name: 'Jane'.age: 20}]function groupBy(objectArray, property) {
    return objectArray.reduce(function (acc, obj) {
        let key = obj[property]
        if(! acc[key]) { acc[key] = [] } acc[key].push(obj)return acc
    }, {})
}

let groupedPeople = groupBy(people, 'age')
console.log(groupedPeople)
/ / {
/ / 20:
// { name: 'Max', age: 20 },
// { name: 'Jane', age: 20 }
/ /,
// 21: [{ name: 'Alice', age: 21 }]
// }
Copy the code

ReduceRight () provides an accumulator for the array, reducing it to a single value (right to left)

The callback function is called once for each element in the array, but indexes in the array that were deleted or never assigned are skipped.

  • Callback A callback function that operates on each element of an array and takes four arguments:

    • Accumulator: The value returned by the callback function when it was last called.

      The first time the callback function is called, the accumulator is initialValue if initialValue exists, otherwise it must be the last element in the array.

    • CurrentValue Current element: The element being processed.

    • Index Indicates the index of the element currently being processed in the optional array.

    • Array Array of optional calls to reduceRight().

  • InitialValue This parameter is optional. The value of the accumulator when the callback function is called for the first time.

    If the initial value is not provided, the last element in the array is used and skipped.

    If no initial value is given, ensure that the array is not empty. Otherwise, calling reduce or reduceRight on an empty array without providing an initial value (e.g. [].reduce((ACC, cur, IDx, arr) => {})) will result in TypeError: Reduce of empty array with no initial value.

The reduceRight callback can be called as follows:

array.reduceRight(function (accumulator, currentValue, index, array) {
    // ...
})
Copy the code

When the callback is called for the first time, There are two possible values for Accumulator and currentValue:

  • If you are callingreduceRightprovidesinitialValueParameter,accumulatorIs equal to theinitialValue.currentValueIs equal to the last element in the array.
  • If not providedinitialValueParameter,accumulatorIs equal to the last element of the array,currentValueEquals the penultimate element in the array.

If the array is empty but provides an initialValue parameter, or if there is only one element in the array and no initialValue parameter is provided, either the initialValue parameter or the element in the array will be returned directly. In either case, the callback function is not called.

Finally, the first call can be summarized in this table:

Number of elements in an array Whether to provideinitialValue The results of
> 1 Did not provide a accumulatorIs the last element in the arraycurrentValueIs the penultimate element
provide accumulatorinitialValue currentValueIs the last element
= 1 Did not provide a Returns the only element in the array
= 0 provide Direct returninitialValue
Did not provide a throwTypeErrorerror

The complete execution of this function is shown in the following example:

[0.1.2.3.4].reduceRight(function (previousValue, currentValue, index, array) {
    return previousValue + currentValue
})
Copy the code

The callback function will be called four times, with the following parameters and return values:

callback previousValue currentValue index array The return value
First call 4 3 3 ,1,2,3,4 [0] 7
Second call 7 2 2 ,1,2,3,4 [0] 9
Third call 9 1 1 ,1,2,3,4 [0] 10
Fourth call 10 0 0 ,1,2,3,4 [0] 10

The reduceRight return value is the return value from the last call to the callback (10).

If an initialValue parameter is provided, the result is as follows:

[0.1.2.3.4].reduceRight(function (previousValue, currentValue, index, array) {
    return previousValue + currentValue
}, 10)
Copy the code
callback previousValue currentValue index array The return value
First call 10 4 4 ,1,2,3,4 [0] 14
Second call 14 3 3 ,1,2,3,4 [0] 17
Third call 17 2 2 ,1,2,3,4 [0] 19
Fourth call 19 1 1 ,1,2,3,4 [0] 20
Fifth call 20 0 0 ,1,2,3,4 [0] 20

At this point, reduceRight returns a value of 20.

// Find the sum of all values in an array
let sum = [0.1.2.3].reduceRight(function (a, b) {
    return a + b
})
console.log(sum) / / 6

// Flatten a two-dimensional array
let flattened = [[0.1], [2.3], [4.5]].reduceRight(function (a, b) {
    return a.concat(b)
}, [])
console.log(flattened) // [4, 5, 2, 3, 0, 1]

// Show the difference between reduce and reduceRight
let a = ['1'.'2'.'3'.'4'.'5']
let left = a.reduce(function (prev, cur) {
    return prev + cur
})

let right = a.reduceRight(function (prev, cur) {
    return prev + cur
})

console.log(left) / / 12345
console.log(right) / / 54321
Copy the code

find()&findIndex()(ES6)

The find method executes a callback function on each element in the array until a callback returns true.

When such an element is found, the method immediately returns the value of the element, otherwise undefined.

Note that the callback function is called for every index in the array from 0 to Length-1, not just the assigned indexes, which means that this method is less efficient for sparse arrays than methods that traverse only the indexes with values.

  • callbackThe function that executes on each item of the array takes three arguments:
    • Element The element currently traversed.
    • indexoptionalThe index currently traversed.
    • arrayoptionalThe array itself.
  • thisArgoptionalUsed when a callback is executedthisThe object.
  1. If thisArg is provided, it will be this for each callback, if not, undefined will be used.

  2. The find method does not change the array.

  3. The index range of the element is determined the first time the callback function is called, so new elements added to the array after the find method starts executing will not be accessed by the callback function.

    If the value of an element in the array that has not been accessed by the callback function is changed by the callback function, then the value will be the current value accessed by the callback function based on its index in the array.

    The deleted element is still accessed, but its value is undefined.

// Use the properties of the object to find the object in the array
let inventory = [
    { name: 'apples'.quantity: 2 },
    { name: 'bananas'.quantity: 0 },
    { name: 'cherries'.quantity: 5}]function findCherries(fruit) {
    return fruit.name === 'cherries'
}

console.log(inventory.find(findCherries)) // {name: "cherries", quantity: 5}

// Find the primes in the array
function isPrime(element, index, array) {
    let start = 2
    while (start <= Math.sqrt(element)) {
        if (element % start++ < 1) {
            return false}}return element > 1
}
console.log([4.6.8.12].find(isPrime)) // undefined returns false if no prime is found
console.log([4.5.8.12].find(isPrime)) / / 5
Copy the code

The findIndex method calls each array index in the array 0.. Leng-1 (inclusive) executes the callback function once until a callback function is found that returns a true (mandatory true) value.

If such an element is found, findIndex immediately returns the index of that element. FindIndex returns -1 if the callback never returns true, or if the length of the array is 0.

Unlike some other array methods, such as Array#some, in a sparse array, the callback function is called even for indexes of items that do not exist in the array.

  • callbackThis callback function is executed for each element in the array, passing the following three parameters automatically:
    • Element The current element.
    • Index Indicates the index of the current element.
    • arraycallfindIndexThe array.
  • thisArgOptional. performcallbackasthisObject value.
  1. If a thisArg argument is provided to findIndex, it will be used as this every time the callback is called. If not provided, undefined will be used.

  2. FindIndex does not modify the array being called.

  3. The index range of the element is determined the first time the callback function is called, so new elements added to the array after the findIndex method starts execution will not be accessed by the callback function.

    If the value of an element in the array that has not been accessed by the callback function is changed by the callback function, then the value will be the current value accessed by the callback function based on its index in the array.

    Deleted elements can still be accessed.

// Find the index of the first prime element in the array
function isPrime(element, index, array) {
    let start = 2
    while (start <= Math.sqrt(element)) {
        if (element % start++ < 1) {
            return false}}return element > 1
}

console.log([4.6.8.12].findIndex(isPrime)) // -1
console.log([4.6.7.12].findIndex(isPrime)) / / 2
Copy the code

keys()&values()&entries()(ES6)

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

const arr = ['a'.'b'.'c']
const iterator = arr.keys()

for (const key of iterator) {
    console.log(key)
}
/ / 0
/ / 1
/ / 2

let arr2 = ['a'.'c']
let sparseKeys = Object.keys(arr)
let denseKeys = [...arr.keys()]
console.log(sparseKeys) / / / "0", "1", "2"]
console.log(denseKeys) // The [0, 1, 2] index iterator contains indexes that have no corresponding element
Copy the code

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

const arr = ['a'.'b'.'c']
const iterator = arr.values()

for (const value of iterator) {
    console.log(value)
}
// a
// b
// c

/ / used for... The of loop iterates
let arr2 = ['w'.'y'.'k'.'o'.'p']
let eArr = arr2.values()

for (let letter of eArr) {
    console.log(letter)
}
//w
//y
//k
//o
//p

// Use.next() iteration
let arr4 = ['a'.'b'.'c'.'d'.'e']
let iterator = arr4.values()
console.log(iterator.next()) // {value: "a", done: false}
console.log(iterator.next().value) // b
console.log(iterator.next()['value']) // c
console.log(iterator.next()) // {value: "d", done: false}
console.log(iterator.next()) // {value: "e", done: false}
console.log(iterator.next()) // {value: undefined, done: true}
console.log(iterator.next().value) // undefined

// If the elements in the array change, the value of the iterator changes
let arr5 = ['a'.'b'.'c'.'d'.'e']
let iterator = arr5.values()
console.log(iterator) // Array Iterator { }
iterator.next().value // "a"
arr5[1] = 'n'
iterator.next().value // "n"
Copy the code

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

// Array Iterator
let arr = ['a'.'b'.'c']
let iterator = arr.entries()
console.log(iterator) // Array Iterator {}

// iterator.next()
console.log(iterator.next()) // {value: [0, "a"], done: false}

// The iterator.next method runs
let a = []

for (let i = 0; i < arr.length; i++) {
    let tem = iterator.next() // Update next with each iteration
    console.log(tem.done) // We can see that done is false after update
    if(tem.done ! = =true) { Done is true when iterating through the iterator
        console.log(tem.value)
        a[i] = tem.value
    }
}
// false
// [1, "b"]
// false
// [2, "c"]
// true
console.log(a) // [[1, "b"],[2, "c"]]
Copy the code

Reference:

JavaScript Advanced Programming version 4

Array MDN

JavaScript forEach, map, filter details

ForEach, map, filter, find, sort, some, etc