Home >Web Front-end >JS Tutorial >Array Extras in JavaScript
JavaScript arrays are a basic data structure in many programming languages, and JavaScript is no exception. To simplify many details of working with arrays, JavaScript provides a set of features called array extension functions. This article introduces various array extension functions and their uses.
Key Points
forEach()
, map()
, filter()
, every()
, some()
, reduce()
, reduceRight()
, indexOf()
, lastIndexOf()
, forEach()
The map()
The forEach()
filter()
function is similar to reduce()
The reduceRight()
indexOf()
method processes each element in the array, computes a single value, while lastIndexOf()
works the same way, but starts at the end of the array. The Background
for
<code class="language-javascript">var foo = ["a", "b", "c", "d"]; for (var i = 0, len = foo.length; i < len; i++) { console.log(foo[i]); }</code>loop to record all elements of an array to the debug console.
First and most importantly, you should understand that the previous example is completely valid JavaScript code. However, if you have several complex loops, tracking variables can become tedious. Array extension functions allow us to replace the entire loop with function calls, which can usually improve the readability of the code. Now, let's take a look at various array extension functions.
forEach()forEach()
Like many array extension functions, the method is a forEach()
higher-order functionforEach()
—a function that receives another function as a parameter.
<code class="language-javascript">var foo = ["a", "b", "c", "d"]; for (var i = 0, len = foo.length; i < len; i++) { console.log(foo[i]); }</code>
Note that using forEach()
eliminates the need for loop and array subscript notation. Additionally, since JavaScript uses function-level scopes, the forEach()
callback function provides a new scope that allows reuse of variable names. The only downside is the performance loss incurred by calling the function for each element in the array. Fortunately, this loss is often negligible. Also note that you can pass an optional parameter to forEach()
after the callback function. If present, the second parameter defines the this
value used in the callback function.
map()
Themap()
function is almost the same as forEach()
. The only difference is that map()
returns an array containing the values returned by the callback function. For example, the following code uses map()
to calculate the square root of each item in the input array. Then return the result as an array and display it. Also note that array extension functions are compatible with built-in JavaScript functions such as Math.sqrt()
.
<code class="language-javascript">["a", "b", "c", "d"].forEach(function(element, index, array) { console.log(element); });</code>
filter()
Like forEach()
and map()
, the filter()
method accepts a callback function and optional this
value. And, like map()
, filter()
returns an array of values based on the return value of the callback function. The difference is that the filter()
callback function should return a boolean value. If the return value is true, add the array element to the result array. For example, the following code removes any element in the original array that does not start with the letter x. In this example, the regular expression (passed as a this
value) will be tested for each array element.
<code class="language-javascript">var sqrts = [1, 4, 9, 16, 25].map(Math.sqrt); console.log(sqrts); // 显示 "[1, 2, 3, 4, 5]"</code>
every() and some()
Theevery()
and some()
functions also run callback functions on each array element. If each callback function returns true, every()
returns true, otherwise false. Similarly, if at least one callback function returns true, some()
returns true. In the following example, every()
and some()
are used to test whether the array element is less than five. In this case, every()
returns false because the last element is equal to five. However, some()
returns true because at least one element is less than five. Note that the index and array parameters exist, but have been omitted from the callback function, as they are not needed in this example.
<code class="language-javascript">["x", "abc", "x1", "xyz"].filter(RegExp.prototype.test, /^x/);</code>
reduce() and reduceRight()
Thereduce()
method processes each element in the array (starting from the beginning) and calculates a single value. reduce()
Prefer the callback function and optional initial value as parameters. If no initial value exists, the first array element is used. reduce()
The callback function is different from the other callback functions we have seen so far in that it accepts four parameters—the previous value, the current value, the index, and the array. A common example of reduce
operations is to add all values of an array. The following example does exactly this. When the callback function is called for the first time, previous
is equal to 1 and current
is equal to 2. In subsequent calls, the sum accumulates to the final value 15.
<code class="language-javascript">var foo = ["a", "b", "c", "d"]; for (var i = 0, len = foo.length; i < len; i++) { console.log(foo[i]); }</code>The
reduceRight()
method works the same way as reduce()
, except that the process starts from the end of the array and moves toward the beginning.
indexOf() and lastIndexOf()
TheindexOf()
method searches for a specific element in the array and returns the index of the first match. If no match is found, indexOf()
returns -1. indexOf()
Please the element to be searched for as its first parameter. The second optional parameter specifies the starting index of the search. For example, the following code looks for the first two occurrences of the letter z in the array. To find the second appearance, we just need to find the first appearance and start searching again from after it.
<code class="language-javascript">["a", "b", "c", "d"].forEach(function(element, index, array) { console.log(element); });</code>The
lastIndexOf()
method works exactly the same way, except that it starts searching from the end of the array.
Conclusion
Use array extension functions to write concise and clear code. Unfortunately, some older browsers do not support these methods. However, you can detect these methods by checking the Array.prototype
object (i.e. Array.prototype.forEach
). If a method is missing, you can easily provide your own implementation.
(The FAQ part should be added here, the content is the same as the FAQ part in the input text, but corresponding pseudo-original modifications are required, such as adjusting the order of the statement, replacing synonyms, etc.)
The above is the detailed content of Array Extras in JavaScript. For more information, please follow other related articles on the PHP Chinese website!