In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-09 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
What are the methods of es6 array? I believe many inexperienced people are at a loss about this. Therefore, this paper summarizes the causes and solutions of the problem. Through this article, I hope you can solve this problem.
The es6 array methods are: "from ()", "of ()", "copyWithin ()", "fill ()", "find ()", "findIndex ()", "includes ()", "entries ()", "keys ()", "values ()" and so on.
The operating environment of this tutorial: windows7 system, ECMAScript version 6, Dell G3 computer.
Traditional Array object method
ToSource () returns the source code for the object.
ToString () converts the array to a string and returns the result.
ToLocaleString () converts the array to a local array and returns the result.
ValueOf () returns the original value of the array object
Modifying the original array does not modify the original array push, popconcatunshift,shiftjoinsortslicereverseindexOf (), lastIndexOf () spliceforEachcopyWithinmapfillfilter
Some
Every
Reduce,reduceRight
Includes
Finde,findIndex
Entries (), keys (), values () modify the original array
Push () adds one or more elements to the end of the array and returns the new length.
Unshift () adds one or more elements to the beginning of the array and returns the new length.
Pop () deletes and returns the last element of the array
Shift () deletes and returns the first element of the array
Sort () sorts the elements of the array
Reverse () reverses the order of the elements in the array.
Splice () deletes the element and adds a new element to the array.
Splice
Grammar
ArrayObject.splice (index,howmany,item1,.,itemX)
Var arr = new Array (); arr [0] = "George"; arr [1] = "John"; arr [2] = "Thomas"; arr.splice (2 William); / / "George", "John" arr.splice (1 William); / / "George", "William", "John" arr.splice (2 Magi 1, ""); / / "George", "William", "" do not modify the original array
Concat () joins two or more arrays and returns the result.
Join () puts all the elements of the array into a string. Elements are separated by the specified delimiter.
Slice () returns the selected element from an existing array
Slice
Grammar
ArrayObject.slice (start,end)
Start is required. Specify where to start the selection. Can be negative, starting at the end of the array.
End is optional. Specifies where to end the selection. If not specified, the shredded array contains all the elements from start to the end of the array. Can be negative, starting at the end of the array.
Var arr = new Array (); arr [0] = "George"; arr [1] = "John"; arr [2] = "Thomas"; arr.slice (2); arr.slice (1); / / "William" arr.slice (- 2); / / "William" converts objects similar to arrays (such as arguments) into real arrays
Array.prototype.slice.call (arguments); add array to ES5
Index method: indexOf (), lastIndexOf ()
Iterative methods: forEach (), map (), filter (), some (), every ()
Merging methods: reduce (), reduceRight ()
Method does not modify the original array
Index method
IndexOf
Array.indexOf (searchElement [, fromIndex])
Returns an integer index value, or-1 if there is no match (exact match).
FromIndex is optional, indicating that the search starts from this location, using the default value of 0 if the default or format does not meet the requirements.
Var data = [2, 5, 7, 3, 5]; console.log (data.indexOf (5, "x")); / / 1 ("x" ignored) console.log (data.indexOf (5, "3")); / / 4 (search from bit 3)
LastIndexOf
Array.lastIndexOf (searchElement [, fromIndex])
Start at the end of the string, not the beginning.
The default value for fromIndex is array.length-1.
Var data = [2, 5, 7, 3, 5]; console.log (data.lastIndexOf (5)); / / 4console.log (data.lastIndexOf (5, 3)); / / 1 (from back to front, start searching with index values less than 3) console.log (data.lastIndexOf (4)) / /-1 (not found) when comparing the first parameter with each item in the array, the two methods use the congruence operator, which requires that it must be exactly equal, otherwise it returns-1.
Iterative method
Each method accepts two parameters, the first parameter callback (callback function, required) and the second parameter is an optional context parameter.
The first parameter, callback, takes three parameters, the value of the current item, the index of the current item in the array, and the array object itself. That is, function (value,index,arr) {}; it is important to note that the first parameter and the second parameter, that is, index and value, are in the opposite order from the methods encapsulated in our commonly used jQuery.
The second parameter is an optional context parameter, which is the scope object that executes the first function parameter, which is the value pointed to by this in the callback mentioned above. If this second optional parameter is not specified, the global object is used instead (window in the browser), or even undefined in strict mode.
It is important to note that except for the forEach () method, the rest of the iterative methods need to have a value of callback, otherwise it will return undefined.
ForEach
ForEach () iterates through the array, running the given function on each item in the array, and this method returns no value.
[] .forEach (function (value, index, array) {/ /...}, [thisObject])
In addition to accepting a required callback function parameter, forEach can also accept an optional context parameter (changing the this point in the callback function) (the second argument).
If this second optional parameter is not specified, the global object is used instead (window in the browser), or even undefined.
ForEach (function (item, index, array) {console.log (Array [index] = item); / / true sum + = item;}); alert (sum); / / 10var database = {users: ["Zhang Hanyun", "Jiang Yiyan", "Li Xiaolu"], sendEmail: function (user) {if (this.isValidUser (user)) {console.log ("Hello," + user) } else {console.log ("Sorry," + user + ", you are not from your family");}}, isValidUser: function (user) {return / ^ Zhang / .test (user);}}; / / email database.users.forEach to everyone (/ / database.users people traversing database.sendEmail, / / send email database / / use database instead of this marked in red) / / result: / / Hello, Zhang Hanyun / / Sorry, Jiang Yiyan, you are not from our family / / Sorry, Li Xiaolu, you are not from our family
Map
Map () means "mapping", which runs a given function on each item in the array and returns an array of results from each function call.
[] .map (function (value, index, array) {/ /...}, [thisObject]); var data = [1,2,3,4]; var arrayOfSquares = data.map (function (item) {return item * item;}); alert (arrayOfSquares); / / 1,4,9,16
Filter
Filter (), "filter", runs a given function on each item in the array and returns an array that meets the filter criteria.
Array.filter (callback, [thisObject])
The callback function of filter needs to return a Boolean value of true or false.
As long as the return value is weak equal to = = true/false, you don't have to return = true/false.
Var arr3 = [1,2,3,4,5,6,7,8,9,10]; var flag = arr3.filter (function (value, index) {return value% 3 = 0;}); console.log (flag); / / [3,6,9]
Every
Every (), which determines whether each item in the array satisfies the given condition, and returns true when all items meet the condition.
Note: if the array is empty, true is returned.
Array.every (callback, [thisObject])
Var arr4 = [1,2,3,4,5]; var flag = arr4.every (function (value, index) {return value% 2 = 0;}); console.log (flag); / / false
Some
Some (), which determines whether there is an item in the array that satisfies the condition, and returns true as long as one item meets the condition.
Note: if the array is empty, false is returned.
Array.some (callback, [thisObject])
Var arr5 = [1,2,3,4,5]; var flag = arr5.some (function (value, index) {return value% 2 = 0;}); console.log (flag); / / true
Merging method
These two methods may be a little more complex than before, both iterating over all the items in the array and then generating a final return value. These two methods receive two parameters.
The first parameter callback, the function accepts four parameters (the initial value total is required, the current value currentValue is required, the index value currentIndex is optional, and the current array arr is optional). The function needs to return a value, which will be used as the initial value in the next iteration.
The second parameter is the iterative initial value (initialValue). The parameter is optional. If it defaults, the initial value is the first item of the array. Starting from the first item of the array, the default parameter needs one less operation than the normal value.
Reduce
The reduce () method takes a function as an accumulator, and each value in the array (from left to right) starts to shrink and eventually evaluates to a value. Reduce () does not execute a callback function for an empty array.
Array. Reduce (function (total, currentValue, currentIndex, array) {
/ /...
});
Var arr9 = [1,2,3,4]; var sum9 = arr9.reduce (function (total, curr, index, array) {return total * curr;}); console.log (sum9); / / 24 var sum9_1 = arr9.reduce (function (total, curr, index, array) {return total * curr;}, 10); console.log (sum9_1); / / 240
ReduceRight
The usage of reduceRight () is similar to that of reduce (), except that reduceRight is implemented at the end of the array.
Array.reduceRight (callback, [thisObject])
Var arr9 = [2,45,30,80]; var flag = arr9.reduceRight (function (total, curr, index) {return total-curr;}); var flag_1 = arr9.reduceRight (function (total, curr, index) {return total-curr;}, 200); console.log (flag); / / 3console.log (flag_1); / / 43
Array method
IsArray
Determines whether the parameter is "Array" and returns true or false.
Var a = [1JI 2jue 3]; Array.isArray (a); / / trueES6 array method
Array method
Array.from ()
Used to turn two types of objects into real arrays: array-like objects (array-like object) and iterable objects (including ES6's new data structures Set and Map).
Let arrayLike = {'0forth:' asides, '1miles:' breadth, '2bands:' cations, length: 3}; let arr2 = Array.from (arrayLike); / / ['averse,' breadth,'c']
Array.from can also accept the second parameter, which acts like the array's map method to process each element and put the processed value into the returned array.
Array.from (arrayLike, x = > x * x); / / equivalent to Array.from (arrayLike) .map (x = > x * x); Array.from ([1,2,3], (x) = > x * x) / / [1,4,9]
Array.of ()
Used to convert a set of values into an array.
Array.of (3 people 11 people 8) / [3 people 11 people 8] Array.of (3) / / [3]
Example method
Will change the original array
CopyWithin ()
Within the current array, copy the members of the specified location to another location (overwriting the original members), and then return to the current array.
Array. CopyWithin (target, start = 0, end = this.length)
Target (required): replace data from this location. If it is negative, it is reciprocal.
Start (optional): read data from this location, default is 0. If it is negative, it is reciprocal.
End (optional): stops reading data before reaching that location, which by default equals the length of the array. If it is negative, it is reciprocal.
/ copy bit 3 to bit 0 [1,2,3,4,5] .copyWithin (0,3,4) / / [4,2,3,4,5] / /-2 equals bit 3, and-1 equals bit 4 [1,2,3,4,5] .copyWithin (0,-2,-1) / / [4,2,3,4,5]
Fill ()
Populates an array with the given value.
Fill (7); / [7,7,7] let arr = new Array (3). Fill ([]); arr [0] .push (5); / / [5], [5]
The original array will not be changed
Find ()
Used to find the first qualified array member. Its argument is a callback function, which is executed by all array members in turn until the first member whose return value is true is found and then returned. If there are no eligible members, undefined is returned.
The callback function of the find method can take three parameters, in turn the current value, the current position, and the original array.
[1,4,-5,10] .find ((n) = > n)
< 0)// -5[1, 5, 10, 15].find(function(value, index, arr) { return value >9;}) / / 10
FindIndex ()
The use of the findIndex method is very similar to the find method, returning the position of the first eligible array member, or-1 if none of the members meet the criteria.
[1,5,10,15] .findIndex (function (value, index, arr) {return value > 9;}) / / 2
Includes ()
Returns a Boolean value indicating whether an array contains the given value.
[1, 2, 3]. True (2) / /
Entries (), keys () and values ()
ES6 provides three new methods: entries (), keys (), and values (), to traverse the array. 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 of the array, values () is the traversal of the key value of the array, and the entries () method is the traversal of the key-value pair of the logarithm.
For (let index of ['asides,' b'] .keys ()) {console.log (index);} / 0Accord / 1for (let elem of ['asides,' b'] .values ()) {console.log (elem);} / / 'b'for (let [index, elem] of [' asides,'b'] .keys ()) {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 the above, have you mastered any methods of es6 array methods? If you want to learn more skills or want to know more about it, you are welcome to 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.