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 > Internet Technology >
Share
Shulou(Shulou.com)05/31 Report--
This article mainly introduces the JavaScript how to operate the array of related knowledge, the content is detailed and easy to understand, the operation is simple and fast, has a certain reference value, I believe you will have something to gain after reading this JavaScript article on how to operate the array, let's take a look at it.
1. Methods related to data structures
Students who have the basic data structure should know the stack and queue data structures (students who do not know can check it by themselves, there is no article recommended). Among the array methods of JavaScript, there are some methods that fit the stack and queue data structures implemented by arrays.
1.1 Array.prototype.push
The push () method adds one or more elements to the end of the array and returns the new length of the array.
Whether to change the original array: yes
Parameters:
ElementN: the element added to the end of the array
Return value: the value of the length attribute after the element is added to the array
This method is similar to the push method in the stack, which places an element on the stack:
Const stack = []; stack.push (1); / / 1 console.log (stack); / / [1] const stack1 = []; stack1.push (1,2); / / 2 console.log (stack1); / / [1,2]
1.2 Array.prototype.pop
The pop () method removes the last element from the array and returns the value of that element. This method changes the length of the array.
Whether to change the original array: yes
Parameter: none
Return value: the element deleted from the array (returns undefined when the array is empty)
This method is similar to the pop-up method in the stack, which pops up the elements at the top of the stack:
Const stack = [1,2,3,4,5]; stack.pop (); / / 5 console.log (stack); / / [1,2,3,4] const stack1 = []; stack1.pop (); / / undefined console.log (stack1); / / []
1.3 Array.prototype.unshift
The unshift () method adds one or more elements to the beginning of the array and returns the new length of the array (this method modifies the original array).
Whether to change the original array: yes
Parameters:
ElementN: the element or elements to add to the beginning of the array
Return value: the value of the length attribute after the element is added to the array
This method is a bit similar to the queuing operation, where one or more elements are queued:
Const queue = [3,4,5]; queue.unshift (2); / / 4 console.log (queue); / / [2,3,4,5] const queue1 = [3,4,5]; queue1.unshift (1,2); / / 5 console.log (queue1); / / [1,2,3,4,5]
1.4 Array.prototype.shift
The shift () method removes the first element from the array and returns the value of that element. This method changes the length of the array.
Whether to change the original array: yes
Parameter: none
Return value: the element deleted from the array (returns undefined when the array is empty)
This method is somewhat similar to the dequeuing operation of the queue and the pop-up operation of the stack:
Const queue = [3,4,5]; queue.shift (); / / 3 console.log (queue); / / [4,5] const queue1 = []; queue1.shift (); / / undefined console.log (queue1); / / []
1.5 Summary
In fact, the reason why it is similar to or somewhat similar is that JavaScript itself does not provide a rigorous method to implement the data structure of queue or stack, but through the flexible use of these four API, you can be more flexible to achieve functions similar to queue or stack. But if you really want to use these four API to simulate a stack or queue in a production environment, you might as well encapsulate it a little bit. Interested students might as well try to learn the knowledge of the stack and the queue later.
1.6 try to do it yourself?
We might as well take a look at how the above API works.
1.6.1 imitating push
Let's start with a push:
Array.prototype.myPush = function (... args) {let top = this.length; for (let I = 0; I)
< args.length; i++) { this[top] = args[i]; top++; } return this.length; }; const stack = []; stack.myPush(1); // 1 console.log(stack); // [1] const stack1 = []; stack1.myPush(1, 2); // 2 console.log(stack1); // [1, 2] 注意:不要使用箭头函数,否则 this 的指向会出现一些问题,关于 this 指向的问题,因为不是本期的重点,所以暂时不聊。 1.6.2 仿写 pop 再试试 pop ? Array.prototype.myPop = function() { const topEle = this[this.length - 1]; this.length >0 & & this.length--; return topEle;}; const stack = [1,2,3,4,5]; stack.myPop (); / / 5 console.log (stack); / / [1,2,3,4] const stack1 = []; stack1.myPop (); / / undefined console.log (stack1); / / []
1.7 Summary
As a digression, write a method, whether it is imitation or self-publication. The first thing to determine is the input parameters and return values of the function, which will not be repeated later. At the same time, I personally tend to write pure functions. As for the imitation of unshift and shift, I won't write it here, it will be a little more troublesome, but it's not too complicated.
two。 Methods related to order
2.1 Array.prototype.sort
The sort () method sorts the elements of the array using the in-place algorithm and returns the array. The default sort order is built when you convert elements to strings and then compare their sequences of UTF-16 code unit values.
Whether to change the original array: yes
Parameters:
CompareFunction: used to specify functions arranged in a certain order. If omitted, the elements are sorted by the Unicode sites of each character of the converted string.
Return value: sorted array (original array)
CompareFunction
Parameters:
A: the first element used for comparison
B: the second element for comparison
Return value: number
Description:
If compareFunction (a, b) is less than 0, then a will be arranged before b
If compareFunction (a, b) equals 0, the relative positions of an and b remain unchanged.
If compareFunction (a, b) is greater than 0, b will be arranged before a
In short, the sort method accepts a callback function. The input parameters of this callback function are the two elements an and b in the array to be compared, and the return value is a number, and sort performs the operation described above on the array based on the value of number.
Look at this: chestnut::
Const numbers = [4,2,5,1,3]; numbers.sort (function (a, b) {return a-b;}); / / [1,2,3,4,5]
Sort this thing, if you expand it, there will be too much content, so we won't expand it here.
2.2 Array.prototype.reverse
The reverse () method reverses the position of the elements in the array and returns the array. The first element of the array becomes the last, and the last element of the array becomes the first. This method changes the original array.
Whether to change the original array: yes
Parameter: none
Return value: upside down array (original array)
There is nothing to say, but to reverse the array, so let's take a look at: chestnut::
Const arr = [1,2,3,4,5]; arr.reverse (); / / [5,4,3,2,1]
3. Methods related to traversal
3.1 Array.prototype.every
The every () method tests whether all elements in an array can pass the test of a specified function. It returns a Boolean value.
Whether to change the original array: no
Parameters:
Callback: callback function
ThisArg: the this value used when executing callback
Return value: boolean (whether all elements pass the callback test)
Callback
Parameters:
Element: the current element when the array executes callback
Index: the index of the current element
Array: the current array of calling methods
Return value: boolean
Description: determine whether the current element meets the criteria of callback
For example: chestnut::
Const test = [1,2,3,4,5]; const isMoreThanThree = (num) = > {return num > 3;}; test.every (isMoreThanThree); / / false
3.2 Array.prototype.some
The some () method tests whether at least one element in the array passes the provided function test. It returns a value of type Boolean.
Whether to change the original array: no
Parameters:
Callback: callback function
ThisArg: the this value used when executing callback
Return value: boolean (whether at least 1 element has passed the callback test)
Callback
Parameters:
Element: the current element when the array executes callback
Index: the index of the current element
Array: the current array of calling methods
Return value: boolean
Description: determine whether the current element meets the criteria of callback
For example: chestnut::
Const test = [1,2,3,4,5]; const isMoreThanThree = (num) = > {return num > 3;}; test.some (isMoreThanThree); / / true
3.3 Array.prototype.find
The find () method returns the value of the first element in the array that satisfies the provided test function. Otherwise, undefined is returned.
Whether to change the original array: no
Parameters:
Callback: callback function
ThisArg: the this value used when executing callback
Return value: the value of the first element in the array that satisfies the provided test function, otherwise undefined is returned.
Callback
Parameters:
Element: the current element when the array executes callback
Index: the index of the current element
Array: the current array of calling methods
Return value: boolean
Description: determine whether the current element meets the criteria of callback
For example: chestnut::
Const test = [1,2,3,4,5]; const isThree = (num) = > {return num = 3;}; const isSeven = (num) = > {return num = 7;}; test.find (isThree); / / 3 test.find (isSeven); / / undefined
3.4 Array.prototype.findIndex
The findIndex () method returns the index of the first element in the array that satisfies the provided test function. If the corresponding element is not found,-1 is returned.
Very similar to the one above, slightly.
3.5 Array.prototype.forEach
The forEach () method executes the given function once on each element of the array.
Whether to change the original array: no
Parameters:
Callback: callback function
ThisArg: the this value used when executing callback
Return value: undefined
Callback
Parameters:
Element: the current element when the array executes callback
Index: the index of the current element
Array: the current array of calling methods
Return value: not required
Think about how you always use this method when you first come into contact with the front end. It's just that the instruction for loop is used to, and the coding habit is not good. In fact, new students can remember this: two no-- do not change the original array, there is no return value (the return value is undefined). All right, for example: chestnut::.
Const test = [1,2,3,4,5]; const log = (val) = > {console.log (val);}; test.forEach (log); / / print 1 2 3 4 5 in turn
3.6 Array.prototype.map
The map () method creates a new array, and the result is that each element in the array is the return value after calling the supplied function once.
Whether to change the original array: no
Parameters:
Callback: callback function
ThisArg: the this value used when executing callback
Return value: Array (a new array consisting of the results of the callback function executed by each element of the original array.)
Callback
Parameters:
Element: the current element when the array executes callback
Index: the index of the current element
Array: the current array of calling methods
Return value: the element that forms the new array
I used to confuse this method with forEach, but now I still haven't learned English well. Map has the meaning of mapping, which is simply explicit. So, map, it will generate an array that maps to the original array. So, for example: chestnut::.
Const test = [1,2,3,4,5]; const double = (num) = > {return num * 2;}; const doubleList = test.map (double); console.log (doubleList); / / [2,4,6,8,10]
3.7 Array.prototype.filter
The filter () method creates a new array that contains all the elements of the test implemented by the provided function.
Whether to change the original array: no
Parameters:
Callback: callback function
ThisArg: the this value used when executing callback
Return value: Array (a new array of elements that pass the test, or an empty array if none of the array elements pass the test.)
Callback
Parameters:
Element: the current element when the array executes callback
Index: the index of the current element
Array: the current array of calling methods
Return value: boolean
Description: determine whether the element passes the test
The naming of this method is easy to understand at a glance, for example: chestnut::
Const test = [1,2,3,4,5]; const isMoreThanThree = (num) = > {return num > 3;}; const moreThanThreeList = test.filter (isMoreThanThree); console.log (moreThanThreeList); / / [4,5]
3.8 Array.prototype.reduce
The reduce () method executes a reducer function (in ascending order) provided by you on each element in the array, summarizing its results into a single return value.
Whether to change the original array: no
Parameters:
Callback: callback function
InitialValue: the value of the first parameter when the callback function is called for the first time. If no initial value is provided, the first element in the array is used. Calling reduce on an empty array with no initial value will report an error.
Return value: the result of the cumulative processing of the function
Callback
Parameters:
Accumulator: the return value of the cumulative callback of the accumulator; it is the cumulative value returned when the callback was last called, or initialValue
Element: the current element when the array executes callback
Index: the index of the current element
Array: the current array of calling methods
Return value: boolean
Description: determine whether the element passes the test
This method, very, very powerful, can be said to work in almost any scenario where you iterate over an array and get a return value.
For example:
Mathematical calculation: accumulation, factorial, find the maximum and minimum value.
Array operation: de-weight, flattening.
Function: pipe (execute function combination from left to right)
Wait
Here we give an implementation of pipe: chestnut::
Const pipe = (... fns) = > {return (arg) = > {return fns.reduce ((res, fn) = > {return fn (res);}, arg);};}
3.9 Summary
It is not difficult to find that API is too similar to methods such as array iteration, but in fact, these API semantics are very good, multi-use, naturally familiar. Then, why don't you implement one by yourself?
3.10 imitating reduce
Array.prototype.myReduce = function (fn, initialValue) {let ret = initialValue | | this [0]; let idx = initialValue? 0: 1; while (idx
< this.length) { ret = fn(ret, this[idx], idx, this); idx++; } return ret; }; const test = [1, 2, 3, 4, 5]; const add = (num1, num2) =>{return num1 + num2;}; test.myReduce (add); / / 15 test.myReduce (add, 10); / / 25
The writing is relatively rough, and the ideas of other methods are similar. Interested students can write for themselves and have a look. After writing, they can more or less deepen their understanding.
4 other methods
4.1 Array.prototype.flat
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.
Whether to change the original array: no
Parameter: depth (specifies the structural depth of the nested array to extract, the default is 1.)
Return value: a flattened array (a new array containing all the elements in the array and subarray.)
I used to think that flattening is of little use in actual production. Until later, when the business I maintained became more complex and needed to use map classification management data to finally take it out and merge it, I found that this method was quite fragrant. For example: chestnut::
Const test = [1, [2,3], [4, [5,6]]; test.flat (1); / [1,2,3,4, [5,6]] test.flat (2); / / [1,2,3,4,5,6]
Can you make it happen for yourself? In fact, I really like the idea of flattening using stacks, which is available on MDN, but I see very little mention of this approach in related articles.
Const test = [1, [2,3], [4, [5,6]]; const flatten = (list) = > {const stack = [... list]; const ret = []; while (stack.length) {const topElem = stack.pop (); if (Array.isArray (topElem)) {stack.push (.. topElem);} else {ret.push (topElem);}} return ret.reverse () }; flatten (test); / / [1,2,3,4,5,6]
In fact, the idea is also relatively easy to think of: flattening the array is obviously a process that requires deep search, and deep search requires the use of stacks, then the stack template is fine. What may need to be reversed a little bit is the last inverted array. Of course, if it is written in full accordance with common sense, then each step into the stack is an inverted element.
This is the end of the article on "how to manipulate arrays in JavaScript". Thank you for reading! I believe you all have a certain understanding of "how to operate arrays in JavaScript". If you want to learn more, you are welcome to follow 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.
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.