Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the methods of JavaScript array operation

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article introduces the relevant knowledge of "what are the methods of JavaScript array operation". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

JavasScript array operations, including Array object prototype methods and common operations such as de-duplication, flattening, sorting, etc.

Array.prototype

ForEach

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

Callback is the function executed by each element in the array, which takes one to three arguments

The index of the current element such as being processed in the currentValue array

Array optional [indicates the array being operated]

ThisArg optional [used as the value of this when the callback function is executed, this parameter will be ignored when using the arrow function]

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

Let arr = [1,2,3,4,5]; let obj = {a: 1}; arr.forEach (function (currentValue, index, array) {console.log ("current value:", currentValue); / / 1 console.log ("current value Index:", index); / / 0 console.log ("current processing array:", array); / / (5) [1, 2, 3, 4, 5] console.log ("current this points to:", this) / / {a: 1} console.log ("end a callback without returning value"); console.log ("");}, obj); console.log (arr); / / [1,2,3,4,5] does not change the original array

Map

Arr.map (callback (currentValue [, index [, array]]) [, thisArg])

Callback is a function executed for each element of the array, which takes one to three arguments

The current element being processed in the currentValue array

Index optional [index of the current element being processed in the array]

Array optional [array being operated]

ThisArg optional [used as the value of this when the callback function is executed, which will be ignored when using the arrow function]

Map () creates a new array that results in the return value of each element in the array after a call to the provided function

Let arr = [1,2,3,4,5]; let obj = {a: 1}; let newArr = arr.map (function (currentValue, index, array) {console.log ("current value:", currentValue); / / 1 console.log ("current value Index:", index); / / 0 console.log ("current processing array:", array); / / (5) [1, 2, 3, 4, 5] console.log ("current this points to:", this) / {a: 1} console.log (""); return crrentValue + 10;}, obj); console.log (newArr); / / [11,12,13,14,15] console.log (arr); / / [1,2,3,4,5] does not change the original array

Push

Arr.push (element1 [,..., elementN])

ElementN is added to the element at the end of the array

Push () adds one or more elements to the end of the array and returns the length of the array

Let arr = ['await,' baked, 'caged,' dashed,'e']; console.log (arr.push ('faded,' g')); / / 7console.log (arr); / / ["a", "b", "c", "d", "e", "f", "g"] change the original array

Pop

Delete the last element in the pop () array and return the value of that element. Return undefind when the array is empty. This method changes the length of the array.

Let arr = [1,2,3,4,5]; console.log (arr.pop ()); / / 5console.log (arr); / / [1,2,3,4] change the original array

Shift

Shift () removes the first element from the array and returns the value of that element, which changes the original array

Let arr = [1,2,3,4,5] console.log (arr.shift ()); / / 1console.log (arr); / / [2,3,4,5] change the original array

Unshift

Arr.unshift (element1 [,..., elementN])

Unshift () adds one or more elements to the beginning of the array and returns the length of the array. This method modifies the original array.

Let arr = [1,2,3,4,5] console.log (arr.unshift (- 1,0)); / / 7console.log (arr); / / [- 1,0,1,2,3,4,5] change the original array

Splice

Arrar.splice (start [, deleteCount [, item1 [, item2 [,...])

Start specifies the starting position of the modification. If the length of the array is exceeded, the content is added from the end of the array; if it is negative, it represents the number of digits starting from the end of the array (counting from-1, which means-n is the nth element from the bottom and equivalent to array.length-1); if the absolute value of the negative number is greater than the length of the array, the start position is the 0th bit.

DeleteCount optional [integer] represents the number of array elements to be removed. If deleteCount is greater than the total number of elements after start, all elements after statr will be deleted (including the start bit). If deleteCount is omitted, or if its value is greater than or equal to array.length-start (that is, if it is greater than or equal to the number of all elements after start), then all elements of the array after start are deleted

Item1, item2,... Optional [elements to be added to the array, starting with the start position. If not specified, splice () will delete only the array elements]

Splice () modifies the array by deleting or replacing existing elements or adding new elements in place, and returns the modified contents as an array. This method changes the original array.

Let arr = [1,2,3,4,5] console.log (arr.splice (1,1)); / / [2] console.log (arr); / / [1,3,4,5] change the original array

Slice

Arr.slice ([begin [, end]])

Begin optional Index at the beginning of extraction starts to extract the original array elements from that index. If the parameter is negative, it is extracted from the penultimate element of the original array. If begin is omitted, slice starts at index 0. If begin is greater than the length of the original array, an empty array is returned.

End optional Index at the end of extraction, where the extraction of the original array elements ends. Slice extracts the index from the original array from begin to end to all elements, including begin, but not end. If end is omitted, slice is extracted all the way to the end of the original array, and if end is greater than the length of the array, slice is also extracted to the end of the array

Slice () returns a new array object, which is a shallow copy determined by begin and end to the original array, including begin, excluding end, and the original array will not be changed

Let arr = [1,2,3,4,5]; console.log (arr.sclice (1,3)); / / [2,3] console.log (arr); / / [1,2,3,4,5] does not change the original array

Concat

Let new_array = old_array.concat (value [, value2 [,... [, valueN])

ValueN optional [] to concatenate an array or value into a new array. If the valueN parameter is omitted, concat returns a shallow copy of the existing array it calls.

Concat () is used to merge two or more arrays. This method does not change the existing array, but returns a new array.

Let arr1 = [1,2,3]; let arr2 = [4,5,6]; let arr3 = arr1.concat (arr2); console.log (arr3); / / [1,2,3,4,5,6] console.log (arr1); / / [1,2,3] does not change the original array

Join

Arr.join ([separator])

Separator optionally specifies a string to separate each element of the array

Join () concatenates all the elements of an array (or a class array object) into a string and returns the string. If the array has only one item, the item is returned without using a delimiter

Let arr = ['a', 'baked,' c']; console.log (arr.join ("&")); / / a&b&cconsole.log (arr); / / ["a", "b", "c"] does not change the array

Sort

Arr.sort ([compareFunction])

CompareFunction is optional to specify functions that are arranged in a certain order. If omitted, the element is sorted by the Unicode of each character converted to the first string

FirstEl's first element for comparison

SecondEl the second element for comparison

Sort () sorts the elements of the array with an in-place algorithm and returns the array. The default sort order is built when you convert elements to strings and then compare their sequences of UTF-16 code unit values

Let arr = [1,2,3,4,5]; console.log (arr.sort ((a, b) = > b-a)); / / [5,4,3,2,1] console.log (arr); / / [5,4,3,2,1] change the original array

Reverse

Reverse () reverses the position of the elements in the array and returns the array, which changes the original array

Let arr = [1,2,3,4,5]; console.log (arr.reverse ()); / / [5,4,3,2,1] console.log (arr); / / [5,4,3,2,1] change the original array

Every

Every () tests whether all elements in an array can pass the test of a specified function and return a Boolean value

Let arr = [1,2,3,4,5]; console.log (arr.every (currentValue = > currentValue > 1)); / / falseconsole.log (arr); / / do not change the original array

Some

Some () Test array whether at least 1 element passes the provided test function and returns a value of type Boolean

Let arr = [1,2,3,4,5]; console.log (arr.some (currentValue = > currentValue > 1)); / / trueconsole.log (arr); / / [1,2,3,4,5] does not change the original array

Filter

Filter () creates a new array containing all the elements that pass the provided test function

Let arr = [1,2,3,4,5]; console.log (arr.filter (currentValue = > currentValue > 2)); / / [3,4,5] console.log (arr); / / [1,2,3,4,5] does not change the original array

Find

Find () returns the value of the first element in the array that satisfies the provided test function, otherwise it returns undefined

Let arr = [1,2,3,4,5]; console.log (arr.find (currentValue = > currentValue > 2)); / / 3console.log (arr); / / [1,2,3,4,5] does not change the original array

FindIndex

FindIndex () returns the index of the first element in the array that satisfies the provided test function, otherwise it returns-1

Let arr = [1,2,3,4,5]; console.log (arr.findIndex (currentValue = > currentValue > 2)); / / 2console.log (arr); / / [1,2,3,4,5] does not change the original array

Includes

Includes () is used to determine whether an array contains a specified value, and returns true if it does, false otherwise

Let arr = [1,2,3,4,5]; console.log (arr.includes (2)); / / trueconsole.log (arr); / / [1,2,3,4,5] does not change the original array

IndexOf

Indexof () returns the first index of the specified element in the array, otherwise-1

Let arr = [1,2,3,4,5]; console.log (arr.indexOf (2)); / / 1console.log (arr); / / [1,2,3,4,5] does not change the original array

LastIndexOf

LastIndexOf () returns the last index of the specified element in the array, or-1 if it does not exist.

Let arr = [1,2,3,2,1]; console.log (arr.lastIndexOf (2)); / / 3console.log (arr); / / [1,2,3,2,1] does not change the original array

Fill

Fill () fills an array with a fixed value from the starting index to the ending index to all elements, excluding the terminating index

Let arr = [1,2,3,4,5]; console.log (arr.fill (0,0,5)); / / [0,0,0,0,0] console.log (arr); / / [0,0,0,0,0] change array

Flat

Flat () recursively traverses the array at a specified depth and merges all elements with the elements in the traversed subarray into a new array.

Let arr = [1,2, [3,4, [5]]; console.log (arr.flat (2)); / / [1,2,3,4,5] console.log (arr); / / [1,2, [3,4, [5] does not change the original array

Keys

Keys () returns an Array Iterator object containing each index key in the array

Let arr = [1,2,3,4,5]; let iterator = arr.keys (); for (const key of iterator) {console.log (key); / / 0 / / 1 / / 2} console.log (arr); / / [1,2,3,4,5] does not change the original array

Common operation

Array deduplication

Working with object

Let arr = [1, 2, 3, 1, 1, 1, 3, 5, 3]; let obj = {}; let newArr = []; arr.forEach (v = > {if (! ogj [v]) {ogj [v] = 1; newArr.push (v);}) console.log (newArr); / / [1,2,3,5]

Use Set

Let arr = [1, 2, 3, 1, 1, 1, 3, 5, 3]; let newArr = Array.from (new Set (arr)); / / let newArr = [... (new Set (arr))]; / / use ES6 to deconstruct assignment console.log (newArr); / / [1, 2, 3, 5]

Flattened array

Use flat

Let arr = [1,2, [3,4, [5]]; let newArr = arr.flat (2); console.log (newArr); / / [1,2,3,4,5]

Recursive implementation of flat

Function _ flat (arr, maxN = 1, curN = 0) {let newArr = []; if (curN > = maxN) return arr; arr.forEach ((v, I, array) = > {if (Array.isArray (v)) {newArr.push (. _ flat (v, maxN, curN + 1));} else newArr.push (v);} return newArr;} let arr = [1,2, [3,4, [5]] Let newArr = _ flat (arr, 1); / / flatten one layer of console.log (newArr); / / [1, 2, 3, 4, [5]]

Count the most characters in a string

Use an array to use the ASCII code of a character as a key to make a bucket

Let s = "ASASRKIADAA"; let arr = []; let base = 65 arr Z65-90 an arr z 97-122Array.prototype.forEach.call (s, (v) = > {let ascii = v.charCodeAt (0)-base; if (arr [ascii]) {+ + arr [ascii];} else arr [ascii] = 1;}) let max = 0ascii maxIndex = 0poliarr.forEach ((v, I) = > {if (v > max) {max = v; maxIndex = I) }}) console.log (String.fromCharCode (maxIndex + base), arr [maxIndex]); / / A 5

Find the maximum value in the array

Ergodic array

Let arr = [1,2,3,1,1,1,3,5,3]; let max =-Infinity;arr.forEach (v = > {if (v > max) max = v;}) console.log (max); / / 5

Use Math

Let arr = [1,2,3,1,1,1,3,5,3]; let max = Math.max (.arr); console.log (max); / / 5

Use reduce

Let arr = [1, 2, 3, 1, 1, 1, 3, 5, 3]; let max = arr.reduce ((a, v) = > {return a > v? A: v;}) console.log (max); / / 5

Copy array

Traversing arrays using push

Let arr = [1,2,3,4,5]; let newArr = []; arr.forEach (v = > newArr.push (v)); console.log (newArr); / / [1,2,3,4,5]

Use concat

Let arr = [1,2,3,4,5]; let newArr = [] .concat (arr); console.log (newArr); / / [1,2,3,4,5]

Use slice

Let arr = [1,2,3,4,5]; let newArr = arr.slice (0); console.log (newArr); / / [1,2,3,4,5]

Randomly disrupt an array

Random exchange N times

Function randomInt (a, b) {return Number.parseInt (Math.random () * (bmura) + a);} let arr = [1,2,3,4,5]; let N = arr.length;arr.forEach ((v, I, arr) = > {let ran = randomInt (0, N); [arr [I], Arran] = [arr [ran], arr [I];}) console.log (arr)

Random ordering

Let arr = [1,2,3,4,5]; arr.sort ((v1, v2) = > {return Math.random () > = 0.5? 1:-1;}) console.log (arr); "what are the methods of JavaScript array operation" is introduced here, thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report