Make writing a habit together! This is the third day of my participation in the “Gold Digging Day New Plan · April More text Challenge”. Click here for more details.
Hello, I’m Yang Chenggong.
In the last article, we learned about arrays in data structures, and summarized the basic operations of arrays in JavaScript, including initializing arrays, adding, modifying, deleting array items, etc., and also summarized JavaScript’s built-in array manipulation functions.
In this article, we’ll take a look at the array iteration and the array capabilities that are new to ES6.
Array iterator
An array is a collection of data, and each element is called an array item. If we want to do something consecutively on each item of the array, we use an iteration of the array, also called a loop, and the for loop is the most basic iteration.
Suppose we now have an array cities like this:
var cities = ['Beijing'.'Shanghai'.'hangzhou'.'shenzhen']
Copy the code
We do this by iterating through the array, prefixing each item with the Chinese – prefix, using a basic for loop:
for(var i = 0; i < cities.length; i++) {
cities[i] = 'China -' + cities[i];
}
// cities = ['中国- Beijing ', '中国- Shanghai ', '中国- hangzhou ', '中国- shenzhen ']
Copy the code
This is the most basic implementation on which JavaScript implements many native iterator functions.
For example, the above loop could be replaced with forEach:
cities.forEach((item, i) = > {
cities[i] = 'China -' + item;
})
// cities = ['中国- Beijing ', '中国- Shanghai ', '中国- hangzhou ', '中国- shenzhen ']
Copy the code
The argument to forEach is a callback function that takes two arguments, the first item representing the current array item and the second parameter representing the index. This function is executed forEach item traversed. The following iterators also take arguments to this callback function:
- map
- filter
- find
- findIndex
- some
- every
We use map to implement the above logic:
cities = cities.map(item= > 'China -' + item)
// cities: ['中国- Beijing ', '中国- Shanghai ', '中国- hangzhou ', '中国- shenzhen ']
Copy the code
See the difference between forEach and Map. ForEach is a direct traversal, pure callback. Map, on the other hand, returns the new value in the callback function and finally returns the new array after execution.
Other functions are used as follows:
// 1. filter
let arr = cities.filter((item, i) = > i==2 || i==3)
// arr: [' Shanghai ', 'hangzhou ']
// 2. find
let row = cities.find(item= > item == 'hangzhou')
// row: 'hangzhou'
// 3. findIndex
let index = cities.findIndex(item= > item == 'hangzhou')
/ / index: 2
Copy the code
The some and every functions are used to check whether an array satisfies certain conditions and return a Boolean value.
// 4. some: checks whether an item in the array satisfies the condition
let bool = cities.some(item= > item == 'hangzhou')
/ / bool: true
// 4. some: checks whether all items in the array meet the criteria
let bool = cities.every(item= > item == 'hangzhou')
/ / bool: false
Copy the code
There is a special iteration function called reduce that has a slightly different but powerful callback function.
Reduce is a function accumulator that adds up values in array items, often by summing up computed values or concatenating strings. Let’s see how we can use reduce to separate the cities array from the cities array:
let str = cities.reduce((total, item) = > total + ', ' + item)
// STR: 'Beijing, Shanghai, Hangzhou, Shenzhen'
Copy the code
Let’s do another example of a sum of numbers. Suppose we have a set of numbers as follows:
let arr = [12.4.16.7.29.4.45.2.52.72.66.4]
let sums = arr.reduce((total, item) = > total + item)
/ / sums: 294.1
Copy the code
Array items are primitive types. Let’s look at an example of an array of objects:
let arr = [
{key: 'd'.val: 13},
{key: 'e'.val: 14},
{key: 'f'.val: 15},]let sums = arr.reduce((total, item) = > {
return total + item.val
}, 0)
/ / sums: 42
Copy the code
As you can see, the reduce callback function, the first parameter total is the sum that has been accumulated, and the second parameter item is the current array item, which is accumulated until the end of the loop to calculate the final value.
Note: The second argument in the reduce method above is 0, which is mandatory and represents the initialization value. If not, the first time the callback is executed, total is the first item and item is the second item. If a value is passed, total is the value and item is the first item in the array.
Other array methods
There are many new array methods in ES6, so let’s take a look.
1. join
Join is used to concatenate all array items as strings, separated by commas by default. Above, we use reduce method to implement array item join. In fact, it is easier to use JOIN:
let str = cities.join(', ');
// STR: 'Beijing, Shanghai, Hangzhou, Shenzhen'
Copy the code
2.slice
The slice method is useful for filtering a contiguous array of subitems. It takes two arguments, the first one is start and the second one is end. The filter rule includes start but not end.
let arr = cities.slice(2.4);
// arr: [' hangzhou, Shenzhen ']
Copy the code
3. includes
The includes method quickly determines whether an array has a specified value. Such as:
let bool = cities.includes('Shanghai');
/ / bool: true
let bool = cities.includes('xi 'an');
/ / bool: false
Copy the code
4. fill
The fill method replaces items in an existing array with a fixed value. It takes three arguments: the first argument value is the value of the replacement, the second argument start is the index to start the replacement, and the third argument end is the index to end the replacement.
For example, replace the third and fourth elements in array Cities with red flags as follows:
cities.fill('Shanghai'.2.4);
// cities: [' Beijing ', 'Shanghai ',' hong ', 'Red flag ']
Copy the code
Note: The fill method changes the array directly.
5. from
The FROM method converts data types with length, as well as iterable objects, to an array. The most common is to convert Set data to an array:
var set = new Set(['Beijing'.'Shanghai'.'Beijing'.'Shanghai'])
let arr = Array.form(set)
// arr: [' Beijing ', 'Shanghai ']
Copy the code
The above operation is called array de-duplication. The FROM method can also separate strings into arrays:
let arr = Array.form('the strongest JavaScript')
/ / arr: [' J ', 'a', 'v', 'a', 'S', 'c', 'r', 'I', 'p', 't', 'the', 'strong']
Copy the code
6. copyWithin
The copyWithin method is also very powerful. Its main function is to select an array of items with two subscripts, and then replace them with those items, starting at the specified location.
Sounds like a mouthful. Go straight to the code. CopyWithin has three parameters. The first parameter is the target from which the replacement starts. Parameter two start is the start position of the filter, and parameter three end is the end position of the filter. Replaces the start-end filtered array entry starting at the target parameter. As follows:
let arr = [1.2.3.4.5]
arr.copyWithin(3.0.2)
// arr: [1, 2, 3, 1, 2]
Copy the code
This method is a bit like slice + fill.
An array of summary
Through two reviews of JavaScript arrays, we learned what arrays are, one of the most commonly used data structures. This will be the basis for other data structures and algorithms.
In the next chapter, we’ll start learning about the second data structure: the stack.
Join a study group
This article source public number: programmer success. This is the first chapter of learning JavaScript data structure and algorithm, this series will be updated for a month, welcome to pay attention to the public account, click “add group” to join me and my friends to learn the team ~