In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
Editor to share with you how JavaScript uses the array method. I hope you will get something after reading this article. Let's discuss it together.
Brief introduction
Description
Brief introduction of the method
Join (): splices each item of the array into a string with the specified delimiter
Push (): add a new element to the end of the array
Pop (): deletes the last item in the array
Shift (): deletes the first item of the array
Unshift (): add a new element to the first bit of the array
Slice (): find out some of the elements according to the condition
Splice (): add and delete the array
Fill (): method can populate one or more elements of an array with specific values
Filter (): filter function
Concat (): used to join two or more arrays
IndexOf (): detects the location index where the current value appears for the first time in the array
LastIndexOf (): detects the location index where the current value last appears in the array
Every (): determines whether each item in the array satisfies the condition
Some (): determines whether there are items in the array that meet the condition
Includes (): determines whether an array contains a specified value
Sort (): sorts the elements of the array
Reverse (): reverse the array
ForEach (): loop through each item in the array (ES5 and below)
Map (): loop through each item in the array (ES6)
CopyWithin (): used to copy elements from a specified location in an array to another specified location in an array
Find (): returns the matching value
FindIndex (): returns the index of the matching position
ToLocaleString (), toString (): converts an array to a string
Flat (), flatMap (): flattened array
Entries (), keys (), values (): traversal array
Create array creation method
JavaScript has the following 11 methods to create arrays:
[1,3,5]; new Array (3); Array (3); Array.apply (null, new Array (3)) Array.apply (null, Array (3)); Array.apply (null, {length: 3}); / / ES6 Array.of (1,2); Array.from ({length: 3}); Array (3) .fill (2); Array (... Array (3)); [... Array (3)]
Example
This is title let arr1 = [1,3,5]; let arr2 = new Array (3); let arr3 = Array (3); let arr4 = Array.apply (null, new Array (3)) let arr5 = Array.apply (null, Array (3)); let arr6 = Array.apply (null, {length: 3}); / / ES6 let arr7 = Array.of (1,2); let arr8 = Array.from ({length: 3}) Let arr9 = Array (3) .fill (2); let arr10 = Array (... Array (3)); let arr11 = [... Array (3)] console.log (arr1); console.log (arr2); console.log (arr3); console.log (arr4); console.log (arr5); console.log (arr6); console.log (arr7); console.log (arr8); console.log (arr9) Console.log (arr10); console.log (arr11)
Brief results:
Detailed results:
Visible:
The following two methods cannot create elements and indexes, only the length attribute
New Array (3); Array (3)
Other methods can create elements, indexes, and length attributes.
Impact on traversal
To forEach, for... In 、 for... The effect of of is the same: for arrays without elements, they are skipped directly, traversing only the values with elements (including undefined).
Detailed explanation
The principle of Array.apply (null, {length: 2})
The principle of Array.apply (null, {length: 2}) is introduced here.
Var arrayLike = {length: 2}
↓↓
Array.apply (null, arrayLike)
↓↓
Array (arrayLike [0], arrayLike [1]) / / pass the value of each element in an empty array to the Array () method one by one
↓↓
Array (undefined, undefined) / / and the value of each element in the empty array is undefined
/ / final output [undefined, undefined]
Mapping transformation
If you want to make further array conversions, you can pass a mapping function as the second argument to the Array.from () method. This function converts each value of the array object to the target form and stores it in the corresponding location of the target array.
Function arga (... args) {return Array.from (args, value = > value + 1);} let arr = arga ('arr', 26,' pop'); console.log (arr); / / ['arr1',27,'pop1']
If the mapping function needs to work on the object, you can manually pass the third parameter to the Array.from () method to specify the this value inside the mapping function.
Const helper = {diff: 1, add (value) {return value + this.diff;}} function translate () {/ / arguments is a class array object return Array.from (arguments, helper.add, helper) corresponding to the parameters passed to the function;} let arr = translate ('liu', 26,' man'); console.log (arr); / / ["liu1", 27, "man1"] method join ()
The join () method is used to convert all the elements in the array into a string.
Elements are separated by a specified delimiter. A comma is used as the delimiter by default.
Var arr = [1mem2 3console.log 3]; console.log (arr.join ()); / / 1meme 2meme3console.log (arr.join ("-")); / / 1-2-3console.log (arr); / / [1JEI 2jue 3] (the original array remains unchanged)
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) {/ / an empty array of length nongl is concatenated into a string with string to form a repetitive return new Array of n string. Join (str);} console.log (repeatString ("abc", 3)); / / abcabcabcconsole.log (repeatString ("Hi", 5); / / HiHiHiHiHipush () and pop ()
The push () method adds elements to the array from the end of the array, and you can add one or more elements.
The pop () method deletes the last element of the array and returns the deleted element.
Var arr = ["Lily", "lucy", "Tom"]; var count = arr.push ("Jack", "Sean"); console.log (count); / / 5console.log (arr); / / ["Lily", "lucy", "Tom", "Jack", "Sean"] var item = arr.pop (); console.log (item); / / Seanconsole.log (arr) / ["Lily", "lucy", "Tom", "Jack"] shift () and unshift ()
The shift () method removes the first element of the array from it and returns the value of the first element.
The unshift () method adds one or more elements to the beginning of the array and returns a new length.
Var arr = ["Lily", "lucy", "Tom"]; var count = arr.unshift ("Jack", "Sean"); console.log (count); / / 5console.log (arr); / / ["Jack", "Sean", "Lily", "lucy", "Tom"] var item = arr.shift (); console.log (item); / / Jackconsole.log (arr) / ["Sean", "Lily", "lucy", "Tom"] sort ()
The sort () method is used to sort the elements of the array.
The sort order can be alphabetic or numeric, in ascending or descending order.
The default sort order is ascending alphabetically.
Var arr1 = ["a", "d", "c", "b"]; console.log (arr1.sort ()); / ["a", "b", "c", "d"] arr2 = [13, 24, 51, 3]; console.log (arr2.sort ()); / / [13, 24, 3, 51] console.log (arr2); / / [13, 24, 3, 51] (the tuple is changed)
To solve the above problem, the sort () method can take a comparison function as an argument so that we can specify which value precedes which value.
The comparison function takes two arguments, returns a negative number if the first parameter should be before the second, 0 if the two parameters are equal, and a positive number if the first parameter should be after the second. Here is a simple comparison function:
Function compare (value1, value2) {if (value1)
< value2) { return -1; } else if (value1 >Value2) {return 1;} else {return 0;}} arr2 = [13,24,51,3]; console.log (arr2.sort (compare)); / / [3,13,24,51]
If you need to produce the result of a descending sort by comparing the function, simply swap the value returned by the comparison function:
Function compare (value1, value2) {if (value1)
< value2) { return 1; } else if (value1 >Value2) {return-1;} else {return 0;}} arr2 = [13, 24, 51, 3]; console.log (arr2.sort (compare)); / / [51, 24, 13, 3] reverse () reverse () method is used to reverse the order of elements in the array. Var arr = [13,24,51,3]; console.log (arr.reverse ()); / / [3,51,24,13] console.log (arr); / / [3,51,24,13] (original array change) 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 arr = [1Jing 3, 5jue 7]; var arrCopy = arr.concat (9, [11je 13]); console.log (arrCopy); / / [1je 3 Jing 5 Jing 7,9,11 Jol 13] console.log (arr); / / [1m 3je 5J 7] (the original array has not been modified)
From the above test results, we can find that if the array is not passed in, the parameters are added directly to the array, and if the array is passed in, each item in the array is added to the array. But what if you pass in a two-dimensional array?
Var arrCopy2 = arr.concat ([9, [11jue 13]]); console.log (arrCopy2); / / [1,3,5,7,9, Array [2]] console.log (arrCopy2 [5]); / / [11mem13] slice ()
Slice (): returns a new array of items from the specified starting subscript to the ending subscript in the original array.
The slice () method can accept one or two parameters, that is, the start and end positions 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 positions, but does not include the item at the end position.
When a negative number appears, add the negative number to the value of the length of the array (6) to replace the number at that position
Var arr = [1meme 3, var arrCopy2 5]; var arrCopy = arr.slice (1); var arrCopy2 = arr.slice (1); var arrCopy3 = arr.slice (1); / / equivalent to arr.slice (1) var arrCopy4 = arr.slice (- 4) console.log (arr); / / equivalent to arr.slice (2) console.log (arr); / [1) (the original array remains unchanged) console.log (arrCopy) / [3,5,7,9,11] console.log (arrCopy2); / / [3,5,7] console.log (arrCopy3); / / [3,5,7] console.log (arrCopy4); / / [5,7,9] splice ()
Splice (): a powerful array method that can be used in many ways to delete, insert, and replace.
1. Delete the element and return the deleted element
You can delete any number of items by specifying two parameters: the location of the first item to delete and the number of items to delete. For example, splice (0Pol 2) deletes the first two items in the array.
Var arr = [1, var arr 3, 5, 5, 7, 7, 9, and 11]; var arrRemoved = arr.splice (0, 2); console.log (arr); / / [5, 5, 7, 9, 11, console.log (arrRemoved); / / [1, 5, 3]
two。 Add an element to the specified index
You can insert any number of items into a specified location by providing three parameters: the starting position, 0 (the number of items to delete), and the item to be inserted. For example, splice (2, 0, 4, 6) inserts 4 and 6 starting at position 2 of the current array.
Var array1 = [22,3,31,12]; array1.splice (1,0,12,35); / / [] console.log (array1); / / [22,12,35,3,31,12]
3. Replace the element at the specified index location
You can insert any number of items into a specified location and delete any number of items at the same time, simply by specifying three parameters: the starting position, the number of items to delete, and any number of items to insert. The number of items inserted does not have to be equal to the number of items deleted. For example, splice deletes the item in position 2 of the current array, and then inserts 4 and 6 starting at position 2.
Const array1 = [22,3,31,12]; array1.splice (1,1,8); / / [3] console.log (array1); / / [22,8,31,12] indexOf () and lastIndexOf ()
Receives two parameters: the item to find and, optionally, an index that represents the location of the starting point for the search.
IndexOf (): start at the beginning of the array (position 0) and look backwards.
LastIndexOf: look forward from the end of the array.
Both methods return the location of the item to be found in the array, or-1 if it is not found. The congruence operator is used when comparing the first parameter with each item in the array.
Var arr = [1Yue3 (5)); console.log (arr.indexOf (5)); / / 2console.log (arr.lastIndexOf (5)); / / 5console.log (arr.indexOf (5)); / / 2console.log (arr.lastIndexOf (5)); / / 2console.log (arr.indexOf ("5")); / /-1forEach ()
ForEach (): iterates over the array, running the given function on each item in the array. This method does not return a value. The parameters are all of function type, which is passed by default.
The parameters are: the contents of the traversed array, the corresponding array index, and the array itself
Var arr = [11, 22, 33, 44, 55]; arr.forEach (function (x, index, a) {console.log (x +'|'+ index +'|'+ (a = arr));})
The output is:
11 | 0 | true
22 | 1 | true
33 | 2 | true
44 | 3 | true
55 | 4 | true
Map ()
The map () method returns a new array whose elements are the values of the original array element after calling the function.
The map () method processes the elements in the order of the original array elements.
This method does not change the original array.
Var arr = [1,2,3,4,5]; var arr2 = arr.map (function (item) {return item*item;}); console.log (arr2); / / [1,4,9,16,25] filter ()
Filter (): filter function, where each item in the array runs a given function and returns an array that meets the filter criteria.
Var arr = [1,2,3,4,5,6,7,8,9,10]; var arr2 = arr.filter (function (x, index) {return index% 3 = 0 | | x > = 8;}); console.log (arr2); / / [1, 4, 7, 8, 9, 10] fill () (added by ES6)
The fill () method can populate one or more elements in an array with specific values. When only one parameter is used, the method populates the entire array with the value of that parameter.
Let arr = [1, 2, 3, 'cc', 5]; arr.fill (1); console.log (arr); / / [1Jing 1JI 1JI 1]
If you don't want to change all the elements in the array, but only some of them, you can use the optional start and end position parameters (excluding the element at the end position).
3 parameters: fill value, start position parameter, end position parameter (excluding the element of the end position)
Let arr = [1d2, 3, 'arr', 5]; arr.fill (1d2); console.log (arr); / / [1d2); console.log (arr); / / [1d2] arr.fill (0pc1,3); console.log (arr); / / [1d0pr 0pr 0je 1jue 1]; every ()
Every (): determines whether each item in the array satisfies the condition, and true is returned only if all items meet the condition.
Var arr = [1,2,3,4,5]; var arr2 = arr.every (function (x) {return x)
< 10;});console.log(arr2); //true var arr3 = arr.every(function(x) { return x < 3;});console.log(arr3); // falsesome() some():判断数组中是否存在满足条件的项,只要有一项满足条件,就会返回 true。 var arr = [1, 2, 3, 4, 5];var arr2 = arr.some(function(x) { return x < 3;});console.log(arr2); //truevar arr3 = arr.some(function(x) { return x < 1;});console.log(arr3); // falseincludes() (ES7) includes() 方法用来判断一个数组是否包含一个指定的值,如果是返回 true,否则 false。 参数有两个,其中第一个是(必填)需要查找的元素值,第二个是(可选)开始查找元素的位置。 const array1 = [22, 3, 31, 12, 'arr'];const includes = array1.includes(31);console.log(includes); // true const includes1 = array1.includes(31, 3); // 从索引3开始查找31是否存在console.log(includes1); // false 需要注意的是:includes使用===运算符来进行值比较,仅有一个例外:NaN 被认为与自身相等。 let values = [1, NaN, 2];console.log(values.indexOf(NaN)); //-1console.log(values.includes(NaN)); //truereduce()和 reduceRight() 这两个方法都会实现迭代数组的所有项(即累加器),然后构建一个最终返回的值。 reduce()方法从数组的第一项开始,逐个遍历到最后。 reduceRight()则从数组的最后一项开始,向前遍历到第一项。 4 个参数:前一个值、当前值、项的索引和数组对象。 var values = [1,2,3,4,5];var sum = values.reduceRight(function(prev, cur, index, array){ return prev + cur;},10); //数组一开始加了一个初始值10,可以不设默认0console.log(sum); //25toLocaleString() 和 toString() 将数组转换为字符串 const array1 = [22, 3, 31, 12];const str = array1.toLocaleString();const str1 = array1.toString(); console.log(str); // 22,3,31,12console.log(str1); // 22,3,31,12find()和 findIndex() find()与 findIndex()方法均接受两个参数:一个回调函数,一个可选值用于指定回调函数内部的 this。 该回调函数可接受三个参数:数组的某个元素,该元素对应的索引位置,以及该数组本身。 该回调函数应当在给定的元素满足你定义的条件时返回 true,而 find()和 findIndex()方法均会在回调函数第一次返回 true 时停止查找。 二者的区别是:find()方法返回匹配的值,而 findIndex()返回匹配位置的索引。 let arr = [1, 2, 3, 'arr', 5, 1, 9]; console.log(arr.find((value, keys, arr) =>{return value > 2;}); / 3 returns the matching value console.log (arr.findIndex ((value, keys, arr) = > {return value > 2;})); / / 2 returns the index copyWithin () (ES6) of the matching position
The copyWithin () method is used to copy elements from the specified location of the array to another specified location of the array.
This method changes the existing array
/ / copy the first two elements of the array to the last two positions of the array let arr = [1mem2, 'arr', 5]; arr.copyWithin (3,0); console.log (arr); / / [1mem2mem3,' console.log 2]
By default, the copyWithin () method is always copied all the way to the end of the array, but you can also provide an optional parameter to limit how many elements will be overwritten. This third parameter specifies the location where the replication stops (excluding the location itself).
Let arr = [1 arr', 2 arr', 5, 9, 17]; / / paste from the position of index 3 / / copy from the position of index 0 / / stop copying arr.copyWithin (3, 0, 3) when you encounter index 3; console.log (arr); / / [1 meme 2 for3) flat () and flatMap () (ES6)
The flat () method recursively traverses the array at a specified depth and merges all elements with the elements in the traversed subarray into a new array.
This method returns a new array with no effect on the original data.
Parameter: specifies the structural depth of the nested array to be extracted, with a default value of 1.
Const arr1 = [0,1,2,3,4]; console.log (arr1.flat ()); / / expected output: [0,1,2,3,4] const arr2 = [0,1,2, [3,4]; console.log (arr2.flat (2)) / / expected output: [0,1,2, [3,4]] / / using Infinity, you can expand a nested array of arbitrary depth var arr4 = [1,2, [3,4, [5,6, [7,8, [9,10]; arr4.flat (Infinity)) / / [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] / / flattening array empty items. If the original array has a vacancy, the flat () method skips the vacancy var arr4 = [1, 2, 4, 5]; arr4.flat (); / / [1, 2, 4, 5]
The flatMap () method executes a function on each member of the original array, which is equivalent to Array.prototype.map (), and then executes the flat () method on the array of return values.
This method returns a new array without changing the original array.
/ equivalent to [[2,4], [3,6], [4,8] .flat () [2,3,4] .flatMap ((x) = > [x, x * 2]) / / [2,4,3,6,4,8] entries (), keys () and values () (ES6)
Entries (), keys (), and values ()-- used to traverse the array. They all return a traversal object that can be traversed with a for...of loop.
The difference is that keys () is the traversal of key names, values () is the traversal of key values, and entries () is the traversal of key-value pairs.
For (let index of ['asides,' b'] .keys ()) {console.log (index);} / 0 / / 1 for (let elem of ['asides,' b'] .values ()) {console.log (elem);} / /'a' / /'b' for (let [index, elem] of ['asides,' b'] .values ()) {console.log (index, elem) } / / 0 "a" / / 1 "b"
If you do not use a for...of loop, you can manually call the next method of the traversal object to traverse.
Let letter = ['averse,' baked,'c']; let entries = letter.entries (); console.log (entries.next () .value); / / [0,'a'] console.log (entries.next () .value); / / [1,'b'] console.log (entries.next () .value) / / [2,'c'] after reading this article, I believe you have some understanding of "how JavaScript uses array methods". If you want to know more about it, please follow the industry information channel. Thank you for reading!
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.