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 commonly used array manipulation methods in JavaScript

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article is to share with you about the array operation methods commonly used in JavaScript, the editor thinks it is very practical, so I share it with you to learn. I hope you can get something after reading this article.

1. Concat ()

The concat () method is used to join two or more arrays. This method does not change the existing array, but only returns a copy of the joined array.

Var arr1 = [1je 2jue 3]; var arr2 = [4je 5]; var arr3 = arr1.concat (arr2); console.log (arr1); / / [1je 2je 3] console.log (arr3); / / [1je 2m 3e, 4je 5] II, join ()

The join () method is used to put all the elements in the array into a string. Elements are separated by the specified delimiter, which is separated by the', 'sign by default and does not change the original array.

Var arr = [2Jing 3jue 4]; console.log (arr.join ()); / / 2Jing 3meme 4console.log (arr); / / [2Jing 3Jing 4] III, push ()

The push () method adds one or more elements to the end of the array and returns a new length. When added at the end, the length is returned, which changes the original array.

Var a = [2 a.push 3 4]; var b = a.push (5); console.log (a); / / 2 console.log (b); / / 4 5, shift ()

The shift () method removes the first element of the array from it and returns the value of the first element. Return to the first element, changing the original array.

Var arr = [2Jing 3jue 4]; console.log (arr.shift ()); / / 2console.log (arr); / / [3Jing 4] VI. Unshift ()

The unshift () method adds one or more elements to the beginning of the array and returns a new length. Return the new length and change the original array.

Var arr = [2 arr.unshift (3)); console.log (arr.unshift (3)); / / 6console.log (arr); / / [3) 6, 2)

Tip: this method does not pass parameters, does not pass parameters, or does not add elements.

7. Slice ()

The slice () method returns a new array of elements from the arrayObject from start to end (excluding this element). Returns the selected element, and this method does not modify the original array.

Var arr = [2 arr.slice (1 recorder 3)); / / [3 recorder 4] console.log (arr); / / [2 recollection 3 Personality 4) 8, splice ()

The splice () method deletes zero or more elements starting at index and replaces those deleted elements with one or more values declared in the parameter list. If you delete an element from arrayObject, an array containing the deleted element is returned. The splice () method modifies the array directly.

Var a = [5, 6, 7, 8]; console.log (a.splice); / / [] console.log (a); / / [5, 9, 6, 6, 7, 7, 8] var b = [5, 9, 6, 6, 7, 7, 8] var b = [5, 9, 6, 6, 7, 8); b.splice (1, 2); / / [6, 3, 8] console.log (b); / / [5, 3, 8] 9, substring () and substr ()

The same point: if you just write a parameter, both serve the same purpose: both intercept the string fragment from the current subscript to the end of the string.

Substr (startIndex); substring (startIndex); var str = '123456789 console.log (str.substr (2)); / / "3456789" console.log (str.substring (2)); / / "3456789"

Difference: the second parameter, substr (startIndex,lenth): the second parameter is to intercept the length of the string (a string of a certain length from the starting point); substring (startIndex, endIndex): the second parameter is to intercept the final subscript of the string (intercept the string between two positions, 'with head and tail').

Console.log ("123456789" .substr (2Jing 5)); / / "34567" console.log ("123456789" .substring (2Jing 5)); / / "345" X, sort sort

Sort by Unicode code position, default ascending order

Var fruit = ['cherries',' apples', 'bananas']; fruit.sort (); / / [apples',' bananas', 'cherries'] var scores = [1, 10, 21, 2]; scores.sort (); / / [1, 10, 2, 21] 11, reverse ()

The reverse () method is used to reverse the order of elements in an array. The upside-down array is returned, which changes the original array.

Var arr = [2Jing 3Jing 4]; console.log (arr.reverse ()); / / [4,3,2] console.log (arr); / / [4,3,2] XII, indexOf and lastIndexOf

Both indexOf and lastIndexOf accept two parameters: the lookup value, the lookup start position does not exist, and returns-1; it exists, and the location is returned. IndexOf is looking from back, lastIndexOf is looking from back to front. IndexOf

Var a = [2,9,9]; a.indexOf (2); / / 0a.indexOf (7); / /-1 if (a.indexOf (7) =-1) {/ / element doesn't exist in array} lastIndexOf var numbers = [2,5,9,2]; numbers.lastIndexOf (2); / / 3numbers.lastIndexOf (7); / /-1numbers.lastIndexOf (2,3); / / 3numbers.lastIndexOf (2,2); / / 0numbers.lastIndexOf (2,-2) / / 0numbers.lastIndexOf (2,-1); / / 3 13. Every logarithmic array

Every runs the given function on each item of the array, and each item returns ture, then true is returned.

Function isBigEnough (element, index, array) {return element

< 10;} [2, 5, 8, 3, 4].every(isBigEnough); // true十四、some some 对数组的每一项都运行给定的函数,任意一项都返回 ture,则返回 true function compare(element, index, array) { return element >

10;} [2,5,8,1,4] .some (compare); / / false [12,5,8,1,4] .some (compare); / / true XV, filter

Filter runs the given function on each item of the array and returns an array of items whose result is ture.

Var words = ["spray", "limit", "elite", "exuberant", "destruction", "present", "happy"]; var longWords = words.filter (function (word) {return word.length > 6;}); / / Filtered array longWords is ["exuberant", "destruction", "present"] 16, map

Runs the given function on each item of the array and returns the result of each function call to form a new array

Var numbers = [1,5,10,15]; var doubles = numbers.map (function (x) {return x * 2;}); / / doubles is now [2,10,20,30] / / numbers is still [1,5,10,15] XVII, forEach array traversal const items = ['item1',' item2', 'item3']; const copy = []; items.forEach (function (item) {copy.push (item)})

The method of adding New Operand Array in ES6

1. Find ():

Pass in a callback function, find the first element in the array that matches the current search rule, return it, and terminate the search.

Const arr = [1, "2", 3, 3, "2"] console.log (arr.find (n = > typeof n = "number")) / / 12, findIndex ():

Pass in a callback function, find the first element in the array that meets the current search rule, return its subscript, and terminate the search.

Const arr = [1, "2", 3,3, "2"] console.log (arr.findIndex (n = > typeof n = "number")) / / 03, fill ():

Replace the elements in the array with the new elements, and you can specify the replacement subscript range.

Arr.fill (value, start, end) 4, copyWithin ():

Select a subscript of the array, and copy the array elements from that location, starting at 0 by default. You can also specify the range of elements to copy.

Arr.copyWithin (target, start, end) const arr = [1pje 2je 3,4,5] console.log (arr.copyWithin (3)) / / [1je 2je 3je 1jue 2] starts with the subscript 3 and copies the array, so 4,5 is replaced by 1, 2const arr1 = [1min2pint 3,4,5] console.log (arr1.copyWithin (3pd1)) / / [1min2pint 3], copy the array from the element with subscript 3. Specify that the subscript of the first copied element is 1, so 4, 5 is replaced by 2, 3const arr2 = [1 from 2 console.log (arr2.copyWithin (3, 1)) / / [1 from 2) / / start with the element with subscript 3, copy the array, specify that the first element to be copied is subscript 1, and the end position is 2, so 4 is replaced with 25, 2.

Convert array-like objects (array-like object) and iterable objects into real arrays

Const bar = ["a", "b", "c"]; Array.from (bar); / / ["a", "b", "c"] Array.from ('foo'); / / ["f", "o", "o"] 6, of

Used to convert a set of values into an array. The main purpose of this method is to make up for the deficiency of the array constructor Array (). Because of the different number of parameters, the behavior of Array () is different.

Array () / / [] Array (3) / / [,] Array (3,11,8) / / [3,11,8] Array.of (7); / / [7] Array.of (1,2,3); / / [1,2,3] Array (7); / / [,] Array (1,2,3) / / [1,2,3] 7, entries () returns iterator: return key-value pair / / array const arr = ['a', 'baked,' c']; for (let v of arr.entries ()) {console.log (v)} / / [0,'a'] [1,'b'] [2,'c'] / Setconst arr = new Set (['a','b','c']) For (let v of arr.entries ()) {console.log (v)} / / ['baked,' b'] ['clocked,' c'] / / Mapconst arr = new Map (); arr.set ('averse,' a'); arr.set ('baked,' b') For (let v of arr.entries ()) {console.log (v)} / / ['asides,' a'] ['baked,' b'] 8, values () returns the iterator: returns the value// array of key-value pairs const arr = ['averse,' baked,'c'] For (let v of arr.values ()) {console.log (v)} / / 'a`b'b' 'c' / / Setconst arr = new Set ([' a', 'baked,' c']); for (let v of arr.values ()) {console.log (v)} / / 'a'b'b'' c' / / Mapconst arr = new Map (); arr.set ('a','a'); arr.set ('baked,' b') For (let v of arr.values ()) {console.log (v)} / /'a''bread9, keys () returns the iterator: returns the key// array of key-value pairs const arr = [' a','b','c']; for (let v of arr.keys ()) {console.log (v)} / / 0 12 / / Setconst arr = new Set (['a','b','c']) For (let v of arr.keys ()) {console.log (v)} / / 'a`b'b'c' / / Mapconst arr = new Map (); arr.set (' axed,'a'); arr.set ('baked,' b'); for (let v of arr.keys ()) {console.log (v)} / /'a' 'broom10, includes

To determine whether the element exists in the array, parameters: the value of the search, the starting position, can replace the ES5 era of indexOf judgment. IndexOf determines whether the element is NaN or not, and it makes an error.

Var a = [1,2,3]; a.includes (2); / / truea.includes (4); / / false are the commonly used array operation methods in JavaScript. The editor believes that there are some knowledge points that we may see or use in our daily work. I hope you can learn more from this article. For more details, please follow the industry information channel.

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