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

2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

What are the methods of javascript array, many novices are not very clear about this, in order to help you solve this problem, the following editor will explain for you in detail, people with this need can come to learn, I hope you can gain something.

In daily development, we will come into contact with some methods of arrays in js, these methods for us, can be very ergodic to achieve the results we want, but because there are many methods, some methods are not commonly used, may be forgotten after a period of time, so here I have sorted out 21 array methods for your reference.

1:concat ()

Function: merge arrays, can merge one or more arrays, will return the data after the merged array, will not change the original array

Var str1 = [12 2, "hello"]; var str2 = ["world"]; console.log (str1.concat (str2)); / / [12jue 2, "hello", "world"] console.log (str1); / / [12Pen2, "hello"]

You can also use the extension operator of es6 without changing the original array

Let str3 = [... str1,...str2] 2:join ()

Function: convert the array to a string and return the converted string data without changing the original array

Note: () use double quotation marks to include the delimiters you want to use. The default is a comma, which is easy to observe here. I used-

Var str1 = [12jue 2, "hello"]; var str2 = ["world"]; console.log (str1.join ("-")); / / 12-2-helloconsole.log (str1); / / [12jue 2, "hello"] 3:pop ()

Function: delete the last bit of the array and return the deleted data, which will change the original array

Var str1 = [12jue 2, "hello"]; console.log (str1.pop () / / helloconsole.log (str1); / / [12jue 2] var str1 = [12je 2, "hello"]; console.log (str1.pop () / / helloconsole.log (str1); / / [12jue 2] 4:shift ()

Function: delete the first bit of the array and return the length of the new array, which will change the original array

Var str1 = [12jue 2, "hello"]; console.log (str1.shift ()); / / 12console.log (str1); / / [2, "hello"] 5:unshift ()

Function: add one or more data to the first bit of the array, and return the length of the new array, which will change the original array

Note: the data returned by the unshift () method is the length of the new array, and the added data can be one or more, which can be understood as adding a series of data.

Var str1 = [12jin2, "hello"]; var str2 = [43pai2, "test"]; console.log (str1.unshift ("Hello")); / / 4console.log (str2.unshift ("hello", "world")); / / 5console.log (str1) / / ["Hello", 12, 2, "hello"] console.log (str2); 6:push ()

Function: add one or more data to the last bit of the array and return the length of the new array, which will change the original array

Note: the push () method returns the length of the new array, and the added data can be one or more, which can be understood as adding a series of data.

Var str1 = [12jue 2, "hello"]; var str2 = [43jue 2, "test"]; console.log (str1.push ("hello")); / / 4console.log (str2.push ("hello", "world")); / / 5console.log (str1); / / [12jue 2, "hello", "hello"] console.log (str2) / / [43, 2, "test", "hello", "world"] 7:reverse ()

Function: invert the data of the array and return the inverted array, which will change the original array.

Var str1 = [12jue 2, "hello"]; console.log (str1.reverse ()); / / ["hello", 2,12] console.log (str1); / / ["hello", 2,12] 8:sort ()

Function: sort the data in the array (the default is ascending order) and return the new array that has been sorted, which will change the original array.

Note:

8.1:

The sorting here is for the sorting of characters. First, use the toString () method of the array to convert to a string, and then compare bit by bit. 3 is greater than 12, because the first bit 3 > 1, do not be confused with Numbertype data sorting.

8.2:

Three characters have been added to the str2 array, and you can see that when comparing, zoom is the largest, because the first English letter can be converted into the corresponding value through the ASCII code, and then compare according to the numerical value.

Var str1 = [12meme 2, hello ", 5 maestro 5," abc "," zoom "]; console.log (str1.sort ()); / / [12pr 2, 2m 43je 5,5] console.log (str1); / / [12jue 2,2je 43je 5,5] console.log (str2.sort ()) / [2,2,43,5,5,92, "abc", "hello", "zoom"] console.log (str2); / / [2,2,43,5,5,92, "abc", "hello", "zoom"] 8.3: scheduling problem

Parameter: sort (callback) if you need to sort by numerical value, you need to pass parameters. Sort (callback), callback is the callback function, which should have two parameters, compare the two parameters, and then return a number indicating the relative order of the two values (Amurb). The returned value is as follows:

If an is less than b, a value less than 0 is returned.

If an equals b, 0 is returned.

If an is greater than b, a value greater than 0 is returned.

Var str3 = [92 str3 2, 43 var str3 5]; console.log (str3.sort (fn)); / / [2 return 2,5,43,92] console.log (str3); / / [2,5,5,43,92] function fn (agin b) {return aLok b;} 9:slice ()

Function: intercept the array at the specified location and return the intercepted array without changing the original array

Parameter: slice (startIndex, endIndex)

Note: you can return the selected element from an existing array. The method receives two parameters slice (start,end), strat is required, indicating which bit to start; end is optional, indicating the end of the bit (excluding end bit), omitting to the last bit; both start and end can be negative, and a negative number means counting from the last bit, such as-1 represents the last bit.

Var arr = ["T1", "J1", "L1", "L2", "M1"]; console.log (arr.slice (1Power3)); / / ["J1", "L1"] console.log (arr.slice (1)); / / ["J1", "L1", "L2", "M1"] console.log (arr.slice (- 4)) / ["J1", "L1", "L2"] console.log (arr.slice (- 2)); / ["Lily", "M1"] console.log (arr.slice); / / ["J1", "L1"] console.log (arr); / / ["T1", "J1", "L1", "L2", "M1"] 10:splice ()

Function: add to the array, remove from the array, or replace elements in the array, and then return the deleted / replaced elements.

Parameter: splice (start,num,data1,data2, …) All parameters are optional. The first parameter is the small mark, the second is the length of the deletion, and the first parameter can be negative.

Var list = [1,2mag3] console.log (list); / / [1,2mag3] / / Delete list.splice (0Power1); / / Delete-> start with 0 subscript and have a length of 1console.log (list); / / [2jue 3] list.splice (0Jue 2); / / Delete-> start with 0 subscript and have a length of 2console.log (list); / / [] / / replace list.splice / / replace-> starting with a subscript of 0, replace array elements of length 1 with 4console.log (list); / / [4Ling 2 Letters 3] list.splice (0meme 2); / / replace-> starting with a subscript of 0, array elements of length 2 are replaced with 4 (that is, 4 pens 2 as a whole) console.log (list); / / [4pc3] / / add list.splice (1pint 0Pol 5) / / add an item 5console.log (list) where the subscript is 1; / / [1mem5pence2pence3]

If the first parameter is negative, count it from the back to the front, enter the figure above.

Splice will change the original array

11:toString ()

Function: converts an array to a string, similar to join () with no parameters. This method is called automatically when the data is implicitly typed or, if manually, converted directly to a string. The original array will not be changed

Var str = [1Jing 2Jue 3]; console.log (str.toString ()); / / 1Jet 2meme 3console.log (str); / / [1Jing 2Jue 3] 12:valueOf ()

Function: returns the original value of the array (usually the array itself), which is usually called by js in the background and does not appear explicitly in the code

Var str = [1je 2jue 3]; console.log (str.valueOf ()); / / [1je 2je 3] console.log (str); / / [1je 2jue 3] / / to prove that the array itself console.log (str.valueOf () = = str) is returned; / / true13:IndexOf ()

Function: according to the specified data, query the location in the array from left to right, if there is no specified data, return-1, find the specified data and return the index of the data

Parameter: indexOf (value, start); value is the data to be queried; start is optional, indicating the location to start the query. If start is negative, it is counted forward from the end of the array; if the query cannot find the existence of value, the method returns-1

Note: if the data is found, the index of the data will be returned immediately, and no further search will be made.

Var str = ["h", "e", "l", "l", "o"]; console.log (str.indexOf ("l")); / / 2console.log (str.indexOf ("l", 3)); / / 3console.log (str.indexOf ("l", 4)); / /-1console.log (str.indexOf ("l",-1)); / /-1console.log (str.indexOf ("l",-3)) / / 214:lastIndexOf ()

Function: according to the specified data, from left to right, the lastIndexOf () method returns the last occurrence of a specified element in the array, looking forward from the back of the string. If the specified data does not exist, return-1, find the specified data and return the index of the data

Parameter: indexOf (value, start); value is the data to be queried; start is optional, indicating the location to start the query. If start is negative, it is counted forward from the end of the array; if the query cannot find the existence of value, the method returns-1

Var str = ["h", "e", "l", "l", "o"]; console.log (str.lastIndexOf ("l")); / / 3

According to my findings, the second parameter of indexOf is useful, and the second parameter of lastIndexOf is the same as if it was not passed.

15:forEach ()

Function: a new method added by ES5 to traverse the array with no return value

Parameters: forEach (callback); callback has three parameters by default, namely value (data from the traversed array), index (corresponding index), and self (array itself).

Var arr = ["Tom", "Jack", "Lucy", "Lily", "May"]; var a = arr.forEach (function (value,index,self) {console.log (value + "-" + index + "- -" (arr = self));}) / / print the result as: / / Tom--0--true// Jack--1--true// Lucy--2--true// Lily--3--true// May--4--trueconsole.log (a) / / undefined---forEach does not return a value / / this method is a traversal method and will not modify the original array 16:map ()

Features:

1. Same as forEach function

The callback function of 2.map returns the execution result, and finally map returns the return values of all callback functions into a new array.

Parameter: map (callback); callback has three parameters by default, which are value,index,self. Same as the parameters of forEach () above

/ / function 1: same as forEach var arr = ["Tom", "Jack", "Lucy", "Lily", "May"] Var a = arr.map (function (value,index) Self) {console.log (value + "- -" + index + "--+ (arr = self)}) / / the printed result is: / / Tom--0--true / / Jack--1--true / / Lucy--2--true / / Lily--3--true / / May--4--true / / function 2: the return value of each callback function is returned by map to form a new array var arr = [" Tom "," Jack "," Lucy " "Lily", "May"] Var a = arr.map (function (value,index,self) {return "hi:" + value;}) console.log (a); / ["hi:Tom", "hi:Jack", "hi:Lucy", "hi:Lily", "hi:May"] console.log (arr); / / ["Tom", "Jack", "Lucy", "Lily", "May"]-- the original array has not changed 17:filter ()

Function: 1. Same as the forEach function; the callback function of 2.filter needs to return a Boolean value. When it is true, the data of this array is returned to filter. Finally, filter returns the return values of all callback functions into a new array (this function can be understood as "filtering").

Parameter: filter (callback); callback has three parameters by default, which are value,index,self.

/ / function 1: same as forEachvar arr = ["Tom", "Jack", "Lucy", "Lily", "May"] Var a = arr.filter (function (value,index,self) {console.log (value + "-" + index + "-" (arr = self)}) / / the printed result is: / / Tom--0--true// Jack--1--true// Lucy--2--true// Lily--3--true// May--4--true// function 2: when the return value of the callback function is true, the array value is returned to filter A new array composed of filter returns var arr = ["Tom", "Jack", "Lucy", "Lily", "May"] Var a = arr.filter (function (value,index,self) {return value.length > 3;}) console.log (a); / / ["Jack", "Lucy", "Lily"] console.log (arr) / ["Tom", "Jack", "Lucy", "Lily", "May"]-the original array has not changed / / function 1: same as forEachvar arr = ["Tom", "Jack", "Lucy", "Lily", "May"] Var a = arr.filter (function (value,index,self) {console.log (value + "-" + index + "-" (arr = self)}) / / the printed result is: / / Tom--0--true// Jack--1--true// Lucy--2--true// Lily--3--true// May--4--true// function 2: when the return value of the callback function is true, the array value is returned to filter A new array composed of filter returns var arr = ["Tom", "Jack", "Lucy", "Lily", "May"] Var a = arr.filter (function (value,index,self) {return value.length > 3;}) console.log (a); / / ["Jack", "Lucy", "Lily"] console.log (arr); / / ["Tom", "Jack", "Lucy", "Lily", "May"]-the original array does not change 18:every ()

Function: determine whether each item in the array meets the condition, and true will be returned only if all items meet the condition.

Parameters: every () takes a callback function as a parameter. This callback function needs a return value, every (callback); callback has three parameters, value,index,self by default.

Function 1: when the return value of the callback function is true, it is similar to the function of forEach and traverses all; if it is false, the execution is stopped, and the subsequent data is no longer traversed, stopping at the first location where false is returned.

/ / demo1: var arr = ["Tom", "abc", "Jack", "Lucy", "Lily", "May"] Var a = arr.every (function (value,index,self) {console.log (value + "-" + index + "--+ (arr = = self)}) / / the printed result is: / / Tom--0--true / / because there is no return true in the callback function, undefined is returned by default, which is equivalent to false / / demo2: var arr = [" Tom "," abc "," Jack "," Lucy "," Lily "," May "] Var a = arr.every (function (value,index,self) {console.log (value + "-" + index + "- -" + (arr = = self)) return value.length

< 4; }) // 打印结果为: // Tom--0--true // abc--1--true // Jack--2--true //因为当遍历到Jack时,回调函数到return返回false,此时Jack已经遍历,但是后面数据就不再被遍历了 //demo3: var arr = ["Tom","abc","Jack","Lucy","Lily","May"]; var a = arr.every(function(value,index,self){ console.log(value + "--" + index + "--" + (arr == self)) return true; }) // 打印结果为: // Tom--0--true // abc--1--true // Jack--2--true // Lucy--3--true // Lily--4--true // May--5--true //因为每个回调函数的返回值都是true,那么会遍历数组所有数据,等同于forEach功能 功能2:当每个回调函数的返回值都为true时,every的返回值为true,只要有一个回调函数的返回值为false,every的返回值都为false //demo1: var arr = ["Tom","abc","Jack","Lucy","Lily","May"]; var a = arr.every(function(value,index,self){ return value.length >

3;}) console.log (a); / / false / / demo2: var arr = ["Tom", "abc", "Jack", "Lucy", "Lily", "May"]; var a = arr.every (function (value,index,self) {return value.length > 2;}) console.log (a); / / true19:some ()

Function: determine whether there are items in the array that meet the condition, and true will be returned as long as one item meets the condition.

Parameters: some () takes a callback function as a parameter. This callback function needs a return value, some (callback); callback has three parameters, value,index,self by default.

Function 1: because to judge every item in the array, as long as a callback function returns true,some, it will return true, so contrary to every, when you encounter a callback function whose return value is true, you can determine the result, then stop execution, and then stop traversing the data and stop at the first position where true is returned. When the return value of the callback function is false, you need to continue to execute backwards until the final result is determined, so it will traverse all the data to achieve a function similar to forEach, traversing all.

/ demo1: var arr = ["Tom", "abc", "Jack", "Lucy", "Lily", "May"]; var a = arr.some (function (value,index,self) {console.log (value + "-" + index + "- -" + (arr = = self)) return value.length > 3 }) / / the printed result is: / / Tom--0--true / / abc--1--true / / Jack--2--true

20.reduce ()

All items in the iterative array, accumulators, and each value in the array (from left to right) are merged and finally calculated to one value.

Parameters:

Callback:

Required for previousValue-the value returned by the last callback, or the initial value provided (initialValue)

Required for currentValue-the array item currently being processed in the array

Index optional-the index value of the current array item in the array

Array optional-primitive array

InitialValue: optional-initial value

How to do it: when the callback function is executed for the first time, preValue and curValue can be a value. If initialValue is provided when reduce () is called, then the first preValue is equal to initialValue, and curValue is equal to the first value in the array; if initialValue is not provided, then preValue is equal to the first value in the array.

Let arr = [0Jing 1, preValue,curValue 2, 3] let arr1 = arr.reduce ((preValue,curValue) = > preValue + curValue) console.log (arr1) / / 10let arr2 = arr.reduce ((preValue,curValue) = > preValue + curValue,5) console.log (arr2) / / 15

Arr.reduce () extension (advanced usage)

(1) calculate the number of occurrences of each element in the array

Let arr = [0Jing 1, preValue,curValue 2, 3] let arr1 = arr.reduce ((preValue,curValue) = > preValue + curValue) console.log (arr1) / / 10let arr2 = arr.reduce ((preValue,curValue) = > preValue + curValue,5) console.log (arr2) / / 15

(2) Array deduplication

Let arr = [1console.log 2 pre.includes 4 console.log 1] let newArr = arr.reduce ((pre,cur) = > {if (! pre.includes (cur)) {return pre.concat (cur)} else {return pre}}, [] console.log (newArr); / /

(3) convert multi-dimensional array to one-dimensional array.

Let arr = [[0,1], [2,3] const newArr = function (arr) {return arr.reduce ((pre,cur) = > pre.concat (Array.isArray (cur)? newArr (cur): cur), []} console.log (newArr (arr)); / / [0,1,2,3,4,5] 21.reduceRight ()

Function: (similar to reduce) start with the last item of the array, iterate through the first bit one by one, iterate over all the items in the array, and then build a final returned value.

Parameter: same as reduce. Demo: same as reduce

22 Array.from ()

Turn a pseudo array into an array, that is, as long as you have length, you can turn it into an array. -es6

Let str = '12345'console.log (Array.from (str)) / / ["1", "2", "3", "4", "5"] let obj = {0str console.log (Array.from (aa)) / [[a "," b "]

The original will not change.

23 Array.of ()

Converts a set of values into an array, similar to declaring an array-es6

Let str = '11'console.log (Array.of (str)) / / [' 11'] / / equivalent to console.log (new Array ('11')) / / [' 11]

Ps: but new Array () has a drawback: overloading caused by parameter problems

Console.log (new Array (2)) / / [empty × 2] is an empty array console.log (Array.of (2)) / / [2] 24 arr.copyWithin ()

Within the current array, copying the positioned array to another location will overwrite the original array item and return the current array

Parameters:

Target-the required index replaces the array item from this location

Start-- the optional index reads the array items from this position, which defaults to 0. 0. If it is negative, read from right to left.

End-optional array items whose index stops reading at this location. The default is Array.length. If it is negative, it represents the reciprocal.

Let arr = [1 console.log (1) console.log (arr1) / / [1] let arr2 = arr.copyWithin (1) console.log (arr2) / / [1, 3) console.log (arr2) / / [1, 3) let arr3 = arr.copyWithin (1 and 2) console.log (arr3) / / [1,3, 4, 4, 5, 6, 7]

Which array methods change the original array

Unshift ()

Push ()

Shift ()

Pop ()

Sort ()

Reverse ()

Splice ()

CopyWithin ()

These eight array methods have been introduced above, and you can see that when you use these methods, the original array will be changed.

What is JavaScript JS is the abbreviation of JavaScript, it is a literal scripting language, its interpreter is called JavaScript engine, is a part of the browser, mainly used for web development, can add a variety of dynamic effects to the website, make the web page more beautiful.

Is it helpful for you to read the above content? If you want to know more about the relevant knowledge or read more related articles, please follow the industry information channel, thank you for your support.

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