In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly introduces "what is the method of javascript es6 array". In the daily operation, I believe that many people have doubts about what the method of javascript es6 array is. The editor consulted all kinds of data and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts of "what is the method of javascript es6 array?" Next, please follow the editor to study!
Es6 array method: 1, map method; 2, find method; 3, findIndex method; 4, filter method; 5, every method; 6, some method; 7, reduce method; 8, reduceRight method; 9, foreach method; 10, keys method and so on.
The operating environment of this tutorial: windows7 system, javascript1.8.5 version, Dell G3 computer.
An array is a collection of data of the same data type in a certain order. In the new version of JavaScript language standard of ES6 (ECMAScript 6), ES6 adds some new features to the array, and these new features expand the ability of the array to process data. In the face of big data collection, it is often possible to complete the work of accumulation, filtering, transformation and so on without cyclic operation. In this article, we will summarize how ES6 provides some new features to arrays.
1. Map method
Each element in the array is processed by a method and the processed array is returned.
Console.clear (); var arr = [12 return currentValue-10; 14 else 34 return currentValue-10; 22 18]; var arr1 = arr.map ((currentValue,index,arr) = > {console.log ("current element" + currentValue); console.log ("current index" + index); if (currentValue > 20) {return currentValue-10;} else {return currentValue-5;}) console.log (arr1) / / another form let nums = [1,2,3]; let obj = {val: 5} Let newNums = nums.map (function (item,index,array) {return item + index + array [index] + this.val;// for the first element, 1 + 0 + 1 + 5 = 7 for the second element, 2 + 1 + 2 + 5 = 10 for the third element, 3 + 2 + 3 + 5 = 13}, obj); console.log (newNums); / / [7,10,13] 2, find and findIndex methods
Retrieving the elements in the array, the find method returns the first element that meets the requirement, and the findIndex method returns the first subscript of the element that meets the requirement.
Console.clear (); var arr = [1214 index 34 22 22 18]; var arr1 = arr.find ((currentValue, index) = > {return currentValue > 20;}) var arr2 = arr.findIndex ((currentValue, index) = > {return currentValue > 20;}) console.log (arr,arr1,arr2); / / the array element is object var allPeple = [{name: 'Xiao Wang', id: 14}, {name: 'King', id: 41}, {name: 'Lao Wang', id: 61}] var PId = 14 / / if this is the person's IDvar myTeamArr = [{name: 'Xiao Wang', id: 14}] function testFunc (item) {return item.id = = PId;} / / determine whether this person is in myteam. If = =-1 means no, find him in allPeople and join my team myTeamArr.findIndex (testFunc) = =-1? MyTeamArr.push (allPeple.find (testFunc)): console.log ('this person already exists') / / retrieve objects var stu = [{name: 'Zhang San', gender: 'male', age: 20}, {name: 'Wang Xiaomao', gender: 'male', age: 20}, {name:'Li Si', gender: 'male', age: 20}] var obj = stu.find ((element) = > (element.name = ='Li Si') console.log (obj); console.log (obj.name) ] .findIndex (function (x) {x = = 2;}); / / Returns an index value of 1. [1recorder 2magin3] .findIndex (x = > x = = 4); / / Returns an index value of-13, filter method
Retrieves the elements in the array and returns all elements that meet the requirements as an array.
Console.clear (); var arr = [12 id 14 text 34 22 22 18]; var arr1 = arr.filter ((currentValue, index) = > {return currentValue > 20;}) console.log (arr,arr1); / / filter var arr for logical attributes = [{id: 1, text: 'aa', done: true}, {id: 2, text:' bb', done: false}] console.log (arr.filter (item = > item.done)) / / retain odd terms let nums = [1,2,3] Let oddNums = nums.filter (item = > item% 2); console.log (oddNums); 4. Every method
Checks whether each element in the array meets the condition, returns true if yes, false otherwise.
Console.clear (); var arr = [12 currentValue 14 index 34 22 22 18]; var arr1 = arr.every ((currentValue, index) = > {return currentValue > 20;}) console.log (arr,arr1); 5. Some method
Checks whether the element in the array meets the condition, and returns true if any, false otherwise.
Console.clear (); var arr = [12 index 14]; var arr1 = arr.some ((currentValue, index) = > {return currentValue > 20;}) console.log (arr,arr1); 6, reduce and reduceRight methods
A function is received as an accumulator (accumulator), and each value in the array (from left to right) is reduced to a value. Reduce accepts a function that takes four parameters: the last value previousValue, the current value currentValue, the index index of the current value, and the array array.
The reduceRight method is the same as the reduce method, which calculates the cumulative count of the array. The difference is that reduceRight () adds the array items in the array forward from the end of the array.
When reduceRight () first calls the callback function callbackfn, prevValue and curValue can be one of two values. If the initialValue parameter is provided when reduceRight () is called, prevValue equals initialValue,curValue equals the last value in the array. If no initialValue parameter is provided, prevValue equals the last value in the array, and curValue equals the penultimate value in the array.
Console.clear (); var arr = [0rect 1je 2je 3je 4]; var total = arr.reduce ((a, b) = > a + b); / / 10console.log (total); var sum = arr.reduce (function (previousValue, currentValue, index, array) {console.log (previousValue, currentValue, index); return previousValue + currentValue;}); console.log (sum) / / if the second parameter is 5, the value of previousValue for the first call will be replaced by var sum1 = arr.reduce (function (previousValue, currentValue, index) {console.log (previousValue, currentValue, index); return previousValue + currentValue;}, 5); console.log (sum1); var sum2 = arr.reduceRight (function (preValue,curValue,index) {return preValue + curValue;}); / / 10var sum3 = arr.reduceRight (function (preValue,curValue,index) {return preValue + curValue) }, 5); / 15 oVal / calculate the sum of squares of the array arr var arr1 = arr.map ((oVal) = > {return oVal*oVal;}) console.log (arr1); var total1 = arr1.reduce ((a, b) = > a + b); / / 30console.log (total1); / / calculate the specified array and let nums = [1,2,3,4,5]; / / accumulate let newNums = nums.reduce (function (preSum,curVal,array) {return preSum + curVal) of multiple numbers }, 0); console.log (newNums) / / 157, foreach method
Loop through the elements of the array, acting like a for loop, with no return value.
Console.clear (); var arr = [12 arr.forEach 14, 34, 22, 18]; var arr1 = arr.forEach ((currentValue, index) = > {console.log (currentValue, index);}) 8, keys,values,entries method
ES6 provides three new methods, entries (), keys (), and values (), for traversing arrays. They all return a traversal object that can be traversed with a for...of loop, except that keys () is the traversal of the key name, values () is the traversal of the key value, and entries () is the traversal of the key-value pair.
Console.clear (); for (let index of ['asides,' b'] .keys ()) {console.log (index);} / / 1for / 1for (let elem of ['ajar,' b'] .values ()) {console.log (elem);} / / 'b'for (let [index, elem] of [' asides,'b'] .keys ()) {console.log (index, elem) } / / 0 "a" / / 1 "b" 9, Array.from static method
The Array.from () method is mainly used to convert two types of objects (array-like objects [array-like object] and traverable objects [iterable]) into real arrays.
Console.clear (); / / objects that are similar to an array are converted to a real array let arrayLike = {'0forth:' aplus.com' / character transfer array let arrayLike = Array.from ('w3cplus.com') / character transfer array console.log (arr) / ["w", "3", "c", "p", "l", "u", "s", ".", "c", "o", "m"] / / Set data transfer array let namesSet = new Set (['aquids,' b']) / / new Set creates a non-repeating element array let arr2 = Array.from (namesSet); / / converts Set structured data into an array console.log (arr2) / / ["a", "b"] / / convert Map data let m = new Map ([1,2], [2,4], [4,8]]); console.log (Array.from (m)); / / [[1,2], [2,4], [4,8]] / / accept the second parameter as the map conversion parameter var arr = Array.from ([1,2,3]) / return a new array var arr1 = Array.from (arr, (x) = > x * x) console.log (arr1); / / [1,4,9] var arr2 = Array.from (arr, x = > x * x); console.log (arr2); / / [1,4,9] var arr3 = Array.from (arr) .map (x = > x * x); console.log (arr3) / / [1,4,9] / large sample generation var arr4 = Array.from ({length:5}, (v, I) = > I); console.log (arr4) / / [0,1,2,3,4] / / the third parameter is the diObj object The this in the map function points to the object / / this function implements the conversion of data let diObj = {handle: function (n) {return n + 2}} console.log (Array.from ([1, 2, 3, 4, 5], function (x) {return this.handle (x)}, diObj)) / / [3, 4, 5, 6, 7] 10, copyWidthin method
The copyWidthin method can copy the array item at the specified location to another location within the current array (overwriting the original array item), and then return the current array. Using the copyWidthin method modifies the current array.
CopyWidthin will accept three parameters [.copyWithin (target, start = 0, end = this.length)]:
Target: this parameter is required to replace the array item from this location
Start: this is an optional parameter. The array item is read from this position. The default is 0. Negative value means reading from the right side of the array to the left.
End: this is an optional parameter, and the array item that stops reading at this location is equal to Array.length by default. If it is negative, it is reciprocal.
Console.clear (); var arr = [1, 2, 3, 4, 5]; / / extract 2 (5-3) elements from subscript 3 to subscript 0var arr = arr.copyWithin (0,3,5); console.log (arr); 11. Fill method
The fill method populates an array with the given value. This method is very convenient for initializing empty arrays. All existing elements in the array are erased.
The fill method can also accept the second and third parameters, which specify the start and end positions of the fill.
Console.clear (); var arr = ['a', 'baked,' cedar,]; arr.fill (0,2,5); console.log (arr); / / ["a", "b", 0,0,0] arr.fill (0,2); console.log (arr); / / ["a", "b", 0,0,0] arr = new Array (5) .fill (0,0,3); console.log (arr) / / [0,0,0, empty × 2] arr = new Array (5) .fill (0,0,5); console.log (arr); / / [0,0,0,0,0] console.log (new Array (3). Fill ({})); / / [{… }, {... }, {... }] console.log (new Array (3). Fill (1)); / / [1,1,1] 12, Set array object usage
ES6 provides a new data structure, Set. It is similar to an array, but the values of the members are unique and there are no duplicate values.
Console.clear (); var s = new Set (); (2) forEach (x = > s.add (x)); console.log (s); / / {2 Ling 3 Ling 4} for (let i of s) {console.log (I);} / / Set object cycle var set = new Set ([1 Meng 2 Meng 3 Meng 4]); / / symbol "..." Convert an array to a comma-separated sequence of parameters console.log ([... set]); / / [1pje 2 pint 3 mae 4] var items = new Set ([1pint 2 pyrrine, 4 pyrrine, 5 pyrrine 5 5,]); console.log (items.size); / / 5, number of elements / / add add element var set = new Set (); set.add ("a"); set.add ("b"); console.log (set) / / {"a", "b"} var s = new Set (); s.add (1) .add (2) .add (2); / / chain add console.log (s.size); console.log (s.has (1)); / / has determines whether element 1 has console.log (s.has (2)); / / trueconsole.log (s.has (3)); / / falses.delete (2) / / delete the second element console.log (s.has (2)); / / false// set rotate the array var items = new Set ([1mai 2je 3je 4je 5]); var array = Array.from (items); console.log (array); / / the map and filter methods of the array can also be indirectly applied to Setvar s = new Set ([1m 2m 3]); s = new Set ([... s] .map (x = > x * 2)) Console.log (s); / {2,4,6} s = new Set ([... s] .filter (x = > (x% 3) = = 0)); console.log (s); / / 6, divisible by 3 / to realize union, intersection, difference var a = new Set ([1m 2m 3]); var b = new Set ([4m 3M 2]); / Union var union = new Set ([... a,... b]); console.log (union) / / intersection var intersect = new Set ([... a] .filter (x = > b.has (x)); console.log (intersect); / / difference var difference = new Set ([... a] .filter (x = >! b.has (x)); console.log (difference); / / ergodic data synchronously change the original Set structure / / use the original Set structure to map a new structure var set1 = new Set Set1 = new Set ([... set1] .map (val = > val * 2)); console.log (set1); / / use Array.fromvar set2 = new Set ([1je 2jue 3]); set2 = new Set (set2, val = > val * 2); console.log (set2); 13. Map array objects
The Map object holds the key-value pair and remembers the original insertion order of the key. Any value (object or original value) can be used as a key or a value. As a set of key-value pair structure, Map has a very fast search speed.
Console.clear (); var names = ['Michael',' Bob', 'Tracy']; var scores = [95,75,85]; / / structure of Map key-value pair var m = new Map ([[' Michael', 95], ['Bob', 75], [' Tracy', 85]]); console.log (m.get ('Michael')); / / 95max / two-dimensional array var m = new Map () needed to initialize Map / / empty Mapm.set ('Adam', 67); / / add new key-valuem.set (' Bob', 59); console.log (m.has ('Adam')); / / whether key' Adam': truem.get ('Adam') exists; / / 67m.delete (' Adam'); / / delete key 'Adam'console.log (m.get (' Adam')) When / / undefined//key is the same, the latter value will wash out the previous value var m = new Map (); m.set ('Adam', 67); m.set (' Adam', 88); console.log (m.get ('Adam')) / / 88
The new version of JavaScript language of ES6 adds a lot of new functions for big data processing to the array, which makes JS have a qualitative improvement in data processing quantity and speed. It is important to note that when we are dealing with a large amount of data, it is recommended to use a Google Chrome browser. ES6 array + Chrome browser changes the data processing function of JS, which is comparable to data processing software such as Python or R language.
Tip: the JS script code on this page can be copied and pasted into the debugging experience of the JS code running window; text editing shortcut key: Ctrl+A-select all; Ctrl+C-copy; Ctrl+X-cut; Ctrl+V-paste
At this point, the study of "what is the javascript es6 array method" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
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.