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 common methods of JS array Array

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

Share

Shulou(Shulou.com)05/31 Report--

Most people do not understand the knowledge points of this article "what are the common methods of JS array Array?", so the editor summarizes the following contents, detailed contents, clear steps, and has a certain reference value. I hope you can get something after reading this article. Let's take a look at this article, "what are the common methods of JS array Array?"

I. the way to create an array in JavaScript

(1) use the Array constructor:

Var arr1 = new Array (); / / create an empty array var arr2 = new Array (15); / / create an array of length 15 var a = new Array ([15]); / / create an array of length 1 with the first bit 15var arr3 = new Array ("sf", "zs", "zsf"); / / create an array of 3 strings

(2) use array literal representation:

Var arr4 = []; / / create an empty array var arr5 = [15]; / / create an array of length 1, containing '15' digits var arr6 = ["sf", "zs", "zsf"]; / / create an array containing three strings.

The method of array is generally distinguished by whether the original array will be changed.

The original data will be changed using the following methods

Whether the method name function array changes pop () to delete the last bit, and returns the deleted data yshift () to delete the first bit, and returns the deleted data ypush to add one or more data at the end, return length yunshift () to add one or more data in the first place, return length ysort () sort (character rule), return result yreverse () reverse array, return result ysplice () to delete the specified position, and replace Returns deleted data y

Using the following methods does not change the original data

Method name function whether the original array changes join () to use the delimiter, converts the array to a string and returns nconcat () merging the array, and returns the merged data nslice () intercepts the array at the specified location, and returns ntoString () directly to the string, and returns nvalueOf () returns the original value of the array object nindexOf () query and returns the index nlastIndexOf () of the data reverse query and returns the index nforEach () parameter of the data is the callback function It iterates through all the items in the array, and the callback function takes three arguments, value,index,self. ForEach does not return the same value nmap () as forEach. At the same time, the callback function returns data, which forms a new array. Map returns nfilter () and forEach, and callback function returns Boolean value. For true data, filter returns nevery () and forEach, while callback function returns Boolean value, all true, truensome () same as forEach, and callback function returns Boolean value. As long as one is true, some returns truenreduce () and merges with forEach. Iterate over all the items of the array and build a final value. Reduce returns nreduceRight () to reverse merge with forEach, iterate all items of the array, and build a final value. ReduceRight returns nfindIndex () to find the subscript of the first qualified element in the array and no longer traverses n 3. Method details 1, pop ()

Pop (): removes the last item at the end of the array, reduces the length value of the array, and then returns the removed item

Ar arr = [1Jing 2jue 3]; console.log (arr.pop ()); / / 3console.log (arr); / / [1Jing 2]-original array change 2, shift ()

Function: the method is used to delete and return the first element of the array.

Var arr = [1Jing 2jue 3] console.log (arr.shift ()); / / 1console.log (arr); / / [2Jue 3]-original array change 3, push ()

Function: adds one or more elements to the end of the array and returns a new length.

Var arr = [1Jing 2jue 3]; console.log (arr.push ("hello")); / / 4console.log (arr); / / [1Yui 2je 3, "hello"]-the original array changes console.log (arr.push ("a", "b")); / / 6console.log (arr); / / [1Jing 2Jing 3, "hello", "a", "b"]-- the original array changes 4, unshift ()

Function: adds one or more elements to the beginning of the array and returns a new length.

Var arr = [1Jing 2jue 3]; console.log (arr.unshift ("hello")); / / 4console.log (arr); / / ["hello", 1je 2jue 3]-the original array changes console.log (arr.unshift ("a", "b")); / / 6console.log (arr); / / ["a", "b", "hello", 1pm 2p3]-the original array changes 5, sort ()

Function: sort the elements in the array. The default is ascending order.

Var arr = [6Jing 1je 5jue 2jue 3]; console.log (arr.sort ()); / / [1,2pint 3,5,6] console.log (arr); / / [1,2pence 3,5,6]-the original array changes

Note: by default, sort converts all elements to String before sorting, while strings are sorted according to ASCII codes.

/ / case 1: seemingly normal results ['Google',' Apple', 'Microsoft'] .sort (); / [' Apple', 'Google',' Microsoft']; / / case 2: apple ranks last ['Google',' apple', 'Microsoft'] .sort () / / ['Google',' Microsoft ", 'apple'] / / case 3: incomprehensible results [10, 20, 1, 2] .sort (); / [1, 10, 2, 20]

If we look at cases 2 and 3, we will find that there is no way to sort complex arrays using sort () directly.

So we can use it as follows

Var arr = [10,20,1,2]; arr.sort ((x, y) = > {if (x)

< y) { return -1; } if (x >

Y) {return 1;} return 0;}); console.log (arr); / / [1,2,10,20] 6, reverse ()

Function: reverses the order of array items.

Var arr = [13,24,51,3]; console.log (arr.reverse ()); / / [3,51,24,13] console.log (arr); / / [3,51,24,13] (original array change) 7, splice ()

Function: a powerful array method that can be used in many ways to delete, insert, and replace.

Array.splice (index, howmany, item1,., itemX)

Index: required. Integer, specify where to add / remove items, and use negative values to specify the location starting at the end of the array

Howmany: optional. The number of items to delete. If set to 0, no items are deleted.

Item1,... , itemX: optional. The new item to add to the array.

The splice () method always returns an array containing items deleted from the original array, or an empty array if no items are deleted.

Var arr = [1meme 3, 5Power9]; var arrRemoved = arr.splice (0meme 2); console.log (arr); / / [5mie 7 pint 9 pint 11] console.log (arrRemoved); / / [1m 3] var arrRemoved2 = arr.splice (2m 0pas 4); console.log (arr); / / [5m 7,4e 6,9 min 11] console.log (arrRemoved2); / / [] var arrRemoved3 = arr.splice (1m 1m 2); console.log (arr) / [5, 2, 4, 4, 6, 9, 11] console.log (arrRemoved3); / / [7] 1, join ()

Function: places all elements in the array into a string according to the specified delimiter and returns the string.

Parameter: join (str); optional, default is the "," sign, with the passed character as the delimiter.

Var arr = [1Jing 2Jue 3]; console.log (arr.join ()); / / 1Jet 2meme 3console.log (arr.join ("-")); / / 1-2-3

You can implement the repeating string through the join () method. You only need to pass in the string and the number of repeats, and the repeated string can be returned. The function is as follows:

Function repeatString (str, n) {return new Array (n + 1) .join (str);} console.log (repeatString ("abc", 3)); / / abcabcabcconsole.log (repeatString ("Hi", 5)); / / HiHiHiHiHi2, concat ()

Function: add parameters to the original array. This method first creates a copy of the current array, then adds the received parameters to the end of the copy, and finally returns the newly built array. Without passing arguments to the concat () method, it simply copies the current array and returns a copy.

Const arr1 = [1Jing 2jue 3]; const arr2 = [4je 5je 6]; const arr3 = arr1.concat (arr2); console.log (arr3); / / [1JI 2je 3J 4m 5J 6] 3, slice ()

Function: returns a new array of items between the starting subscript and the ending subscript specified in the original array.

Array.slice (start, end)

The slice () method can accept one or two parameters, namely, the start (start) and end position (end) of the item to be returned.

In the case of only one parameter, the slice () method returns all items from the specified position of that parameter to the end of the current array.

If there are two parameters, the method returns the item between the start and end position-- but does not include the item at the end position.

If start > end's index, an empty array is returned

Var arr = [1meme 3jorie 5ju 7jue 9ju 11]; var arrCopy1 = arr.slice (1); var arrCopy2 = arr.slice (1pas 4); var arrCopy3 = arr.slice (1mai Leim 2); var arrCopy4 = arr.slice (- 4m Linda1); console.log (arr); / / [1m 3m 5m 7e 7m 9J 11] (original array unchanged) console.log (arrCopy1); / [3pr 5e 7e 9m 11] console.log (arrCopy2) / / [3,5,7] console.log (arrCopy3); / / [3,5,7] console.log (arrCopy4); / / [5,7,9] 4, toString ()

Function: convert 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.

Var arr = [1Jing 2Jue 3]; console.log (arr.toString ()); / / 1Jet 2meme 3console.log (arr); / / [1Jing 2Jing 3]-the original array has not changed 5, 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 arr = [1je 2jue 3]; console.log (arr.valueOf ()); / / [1je 2je 3] console.log (arr); / / [1je 2jue 3] / / to prove that the array itself is returned console.log (arr.valueOf () = = arr); / / true6, indexOf ()

Function: according to the specified data, from left to right, query the location in the array, if there is no specified data, return-1. This method is a query method and does not change the array.

IndexOf (value, start)

Value: data to be queried

Start: optional, indicating where to start the query, counting forward from the end of the array when start is negative; if the query cannot find the existence of value, the method returns-1

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

Function: according to the specified data, from right to left, query the location in the array, if there is no specified data, return-1. This method is a query method and does not change the array.

LastIndexOf (value, start)

Value: data to be queried

Start: optional, indicating where to start the query, counting forward from the end of the array when start is negative; if the query cannot find the existence of value, the method returns-1

Var arr = ["h", "e", "l", "l", "o"]; console.log (arr.lastIndexOf ("l")); / / 3console.log (arr.lastIndexOf ("l", 3)); / / 3console.log (arr.lastIndexOf ("l", 1)); / /-1console.log (arr.lastIndexOf ("l",-3)); / / 2console.log (arr.lastIndexOf ("l",-4)) / /-18, forEach ()

Function: iterate through the array and run a given function on each item in the array. This method does not return a value.

Parameters: all are of function type. Parameters are passed by default. The parameters are the contents of the array traversed, the corresponding array index, and the array itself.

Var arr = [1,2,3,4,5]; arr.forEach ((item, index, a) = > {console.log (item +'|'+ index +'|'+ (a = arr)); / / output: / / 1 | 0 | true// 2 | 1 | true// 3 | 2 | true// 4 | 3 | true// 5 | 4 | true9, map ()

Function: runs a given function on each item in the array and returns an array of results of each function call.

Use map if you want every value in the array to change

Let arr = [10,30,50,60,120,230,340,450] let newArr = arr.map (item = > {return item * 2}) console.log (newArr); / / [20,60,100,120,240,460,680,900] console.log (arr); / / [10,30,50,60,120,230,340,450] 10, filter ()

Function: filter, each item in the array runs a given function and returns an array that meets the filtering criteria.

/ filter out elements with an index of 3 or values greater than 8 var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; var arr2 = arr.filter ((item, index) = > {return index% 3 = 0 | item > = 8;}); console.log (arr2); / / [1, 4, 7, 8, 9, 10] 11, every ()

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

Var arr = [1,2,3,4,5]; var arr2 = arr.every ((x) = > {return x

< 10;}); console.log(arr2); //truevar arr3 = arr.every((x) =>

{return x

< 3;}); console.log(arr3); // false12、some() 功能: 判断数组中是否存在满足条件的项,只要有一项满足条件,就会返回true。 var arr = [1, 2, 3, 4, 5];var arr2 = arr.some((x)=>

{return x

< 3;}); console.log(arr2); //truevar arr3 = arr.some((x)=>

{return x

< 1;}); console.log(arr3); // false13、reduce() 功能:从数组的第一项开始,逐个遍历到最后,迭代数组的所有项,然后构建一个最终返回的值。 array.reduce(function(total, currentValue, currentIndex, arr), initialValue) 参数: total是当前聚合值即合并的值,他可以是任何类型 currentValue是数组循环时的当前元素 currentIndex 是数组元素的索引值 arr是数组本身 initialValue传递给函数的初始值 一般常用的是前面的两个参数,后面两个参数不常用,常用的使用场景便是数组的求和 // 作用:对数组中所有的内容进行汇总 要传至少两个值 let arr = [10, 30, 50, 60, 120, 230, 340, 450] let newArr = arr.reduce((pre, n) =>

{return pre + n}, 0) console.log (newArr); 14, 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.

Array.reduceRight (total, currentValue, currentIndex, arr), initialValue)

Parameter: same as reduce.

Var arr = [1Jing 2 Jing 3 Jing 4 Jing 5]; var sum = arr.reduceRight (pre, cur, index, array) {return pre + cur;}, 10); console.log (sum); / / 2515, findIndex ()

Function: returns the index of the first element in the array that satisfies the provided test function. If not, return-1.

Let arr = [10,2,9,17,22]; let index = arr.findIndex ((item) = > item > 13) console.log (index); / / 3 IV.

We can use this method to implement some algorithms. Here I will only write some simple methods that can be implemented.

4.1. Implement array sorting (ascending order | | descending order)

We can use sort with reverse to sort quickly, but we can also use bubble sort, quick sort and so on.

The principle of sort itself is a way of writing bubble sorting.

Ascending order

Var arr = [6, 1, 5, 5, 2, 3]; console.log (arr.sort ()); / / [1, 2, 5, 6]

Descending order

Var arr = [6Jing 1Jing 5jue 2jue 3]; console.log (arr.sort ((arecine b) = > {return b-a})); / / [6Jing 5Jing 4Jing 3JI 2J1]

Descending order

Var arr = [6Jing 1je 5je 2jue 3]; console.log (arr.sort (). Reverse ()); / / [6pr 5je 4je 3je 2je 1] 4.2, array de-duplication

Suitable for indexOf and push implementation

Function uniqueArray (arr) {var temp = []; for (var I = 0; I

< arr.length; i++) { if (temp.indexOf(arr[i]) == -1) { temp.push(arr[i]); } } return temp;} 使用filter去重 var r = [],arr = ['apple', 'strawberry', 'banana', 'pear', 'apple', 'orange', 'orange', 'strawberry'];r = arr.filter(function (element, index, self) { return self.indexOf(element) === index;});consolo.log(r)//['apple', 'strawberry', 'banana', 'pear', 'orange'] 使用reduce实现数组对象去重 //数组重名去重var resources = [ { name: "张三", age: "18" }, { name: "张三", age: "19" }, { name: "张三", age: "20" }, { name: "李四", age: "19" }, { name: "王五", age: "20" }, { name: "赵六", age: "21" }]var temp = {};resources = resources.reduce((prev, curv) =>

{if (! temp [curv.name]) {/ / add this name if the temporary object does not exist, and add the current object to the prev temp [curv.name] = true; prev.push (curv);} return prev}, []); console.log (resources) / / [/ {name: "Zhang San", age: "18"}, / / {name: "Li Si", age: "19"}, / / {name: "Wang Wu", age: "20"}, / / {name: "Zhao Liu", age: "21"} / / 4.3, find array elements

The element that repeats the most times in the array

Var arr = [1 obj, 1 maxName, 2, 2, 2, 2, 2, 2, 2, 3, 3, 4, 4, 4, 4, 4, 4, 5, 6, 7, 7, and 8]; var maxNum = 0There var maxName = ""; var obj = {}; arr.forEach ((ele,index) = > {obj [ele]? Obj [ele] + = 1: obj [ele] = 1 }) for (let r in obj) {if (OBJ [r] > maxNum) {maxNum = obj [r] maxName = r}} console.log (`maximum number of repeats ${maxName}, number of repetitions: ${maxNum} `) / / number of repeats up to 2. The number of repetitions above 7 is the content of the article "what are the common methods of Array in JS arrays"? I believe we all have a certain understanding. I hope the content shared by the editor will be helpful to you. If you want to know more about the relevant knowledge, please pay attention to 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