1, js array summary
1. Create (from/of)
1.Array() constructor
- There are several basic ways to create arrays. One is to use the Array constructor, such as:
There are several basic ways to create arrays. One is to use Array Constructor, for example: let colors = new Array(); If you know the number of elements in the array, you can pass a value to the constructor and length The attribute will be automatically created Build and set to this value. For example, the following code will create an initial length Array of 20: let colors = new Array(20); You can also give Array Constructor passes in the element to save. For example, the following code will create a string containing three string values Array: let colors = new Array("red", "blue", "green"); When you create an array, you can pass a value to the constructor. At this point, there is a problem, because if the value is a value, a new value will be created An array with a length of the specified value; If the value is of another type, an array containing only that specific value is created. Look below An example: let colors = new Array(3); // Create an array of 3 elements let names = new Array("Greg"); // Create an array that contains only one element, the string "Greg" in use Array Constructor can also be omitted new Operator. The result is the same, for example: let colors = Array(3); // Create an array of 3 elements let names = Array("Greg"); // Create an array that contains only one element, the string "Greg"
2. Literal quantity
Another way to create an array is to use array literals( array literal)Representation. Array literals are contained in square brackets with Comma separated element list, as shown in the following example: let colors = ["red", "blue", "green"]; // Create an array of 3 elements let names = []; // Create an empty array let values = [1,2,]; // Create an array of 2 elements In this example, the first line creates an array of three strings. The second line creates an empty array with a pair of empty parentheses. The third line shows the effect of adding a comma after the last value of the array: values Is an array of two values (1 and 2).
As with objects, the Array constructor is not called when an Array is created using Array literal notation.
3.es6 static creation method
- from(): used to convert the class array structure into an array instance
- of(): used to convert a set of parameters into array instances
1.Array.from()
The first parameter is a class array object, that is, any iteratable structure, or a structure with a length attribute and indexable elements. This method can be used in many situations:
// The string is split into a single character array console.log(Array.from("Matt")); // ["M", "a", "t", "t"] // You can use from() to convert the collection and mapping into a new array const m = new Map().set(1, 2).set(3, 4); const s = new Set().add(1).add(2).add(3).add(4); console.log(Array.from(m)); // [[1, 2], [3, 4]] console.log(Array.from(s)); // [1, 2, 3, 4] // Array.from() performs a shallow copy of an existing array const a1 = [1, 2, 3, 4]; const a2 = Array.from(a1); console.log(a1); // [1, 2, 3, 4] alert(a1 === a2); // false // You can use any iteratable object const iter = { *[Symbol.iterator]() { yield 1; yield 2; yield 3; yield 4; } }; console.log(Array.from(iter)); // [1, 2, 3, 4] // The arguments object can be easily converted into an array function getArgsArray() { return Array.from(arguments); } console.log(getArgsArray(1, 2, 3, 4)); // [1, 2, 3, 4] // from() can also convert custom objects with the necessary attributes const arrayLikeObject = { 0: 1, 1: 2, 2: 3, 3: 4, length: 4 }; console.log(Array.from(arrayLikeObject)); // [1, 2, 3, 4]
The second optional mapping function parameter. This function can directly enhance the value of the new array without calling array from(). Create an intermediate array like map ().
The third optional parameter is used to specify the value of this in the mapping function. However, this rewritten this value does not apply in the arrow function.
const a1 = [1, 2, 3, 4]; const a2 = Array.from(a1, x => x**2); const a3 = Array.from(a1, function(x) {return x**this.exponent}, {exponent: 2}); console.log(a2); // [1, 4, 9, 16] console.log(a3); // [1, 4, 9, 16]
2.Array.of()
You can convert a set of parameters into an array. This method is used to replace the array prototype. slice. Call (arguments), an extremely clumsy way to convert arguments objects into arrays:
console.log(Array.of(1, 2, 3, 4)); // [1, 2, 3, 4] console.log(Array.of(undefined)); // [undefined]
2. Array vacancy
When initializing an array with array literals, you can use a string of commas to create hole s. ECMAScript will treat the value of the corresponding index position between commas as as spaces. ES6 specification redefines how to deal with these spaces.
You can create an array of empty bits as follows: const options = [,,,,,]; // Create an array of 5 elements console.log(options.length); // 5 console.log(options); // [,,,,,]
The new methods and iterators in ES6 behave differently from those existing in earlier ECMAScript versions. The new method of ES6 generally regards these vacancies as existing elements, but the value is undefined:
const options = [1,,,,5]; for (const option of options) { console.log(option === undefined); } // false // true // true // true // false const a = Array.from([,,,]); // Array. Using ES6 An array of three empty bits created by from() for (const val of a) { alert(val === undefined); } // true // true // true alert(Array.of(...[,,,])); // [undefined, undefined, undefined] for (const [index, value] of options.entries()) { alert(value); } // 1 // undefined // undefined // undefined // 5
The method before ES6 will ignore this vacancy, but the specific behavior will also vary according to the method:
const options = [1,,,,5]; // map() skips empty locations console.log(options.map(() => 6)); // [6, undefined, undefined, undefined, 6] // join() treats the null position as an empty string console.log(options.join('-')); // "1----5"
Due to inconsistent behavior and potential performance hazards, array vacancies should be avoided in practice. If you do need a vacancy, you can explicitly replace it with an undefined value.
3. Array index
let colors = ["red", "blue", "green"]; // Create an array of 3 strings colors[99] = "black"; // Add a color (position 99) alert(colors.length); // 100
Here, a value of the colors array is inserted into position 99, and the new length becomes 100 (99 + 1). All elements in the middle, i.e. positions 3 ~ 98, do not actually exist, so undefined will be returned when accessing.
4. Detection array (isarray)
A classic ECMAScript problem is to judge whether an object is an array. When there is only one web page (and therefore only one global scope), the instanceof operator is sufficient:
if (value instanceof Array){ // Operation array }
The problem with instanceof is to assume that there is only one global execution context. If there are multiple frames in the web page, two different global execution contexts may be involved, so there will be two different versions of Array constructors. If you want to pass an Array from one frame to another, the constructor of this Array will be different from the Array created locally in the second frame.
To solve this problem, ECMAScript provides array Isarray() method. The purpose of this method is to determine whether a value is an array, regardless of the global execution context in which it is created. Consider the following example:
if (Array.isArray(value)){ // Operation array }
5. Iterator method (keys/values/entries)
In ES6, three methods for retrieving Array contents are exposed on the prototype of Array:
keys()Returns the iterator of the array index values()Returns the iterator of an array element entries()Return index/Iterator of value pair
const a = ["foo", "bar", "baz", "qux"]; // Because these methods all return iterators, their contents can be // Through array From() is directly converted to an array instance const aKeys = Array.from(a.keys()); const aValues = Array.from(a.values()); const aEntries = Array.from(a.entries()); console.log(aKeys); // [0, 1, 2, 3] console.log(aValues); // ["foo", "bar", "baz", "qux"] console.log(aEntries); // [[0, "foo"], [1, "bar"], [2, "baz"], [3, "qux"]]
Using the deconstruction of ES6, it is very easy to split key / value pairs in a loop:
const a = ["foo", "bar", "baz", "qux"]; for (const [idx, element] of a.entries()) { alert(idx); alert(element); } // 0 // foo // 1 // bar // 2 // baz // 3 // qux
6. Copy and fill method (fill/copyWithin)
1.fill()
`ES6` Two new methods are added: -Batch copy method copyWithin(), -And the method of filling the array fill(). Contains the start index, not the end index. Using this method does not change the size of the array fill()Method can insert all or part of the same value into an existing array. -The start index is used to specify where to start the population. It is optional. -If the end index is not provided, it is filled to the end of the array. -The negative index is calculated from the end of the array. You can also think of a negative index as an array length plus a positive index:
const zeroes = [0, 0, 0, 0, 0]; // Fill the entire array with 5 zeroes.fill(5); console.log(zeroes); // [5, 5, 5, 5, 5] zeroes.fill(0); // Reset // Fill elements with index greater than or equal to 3 with 6 zeroes.fill(6, 3); console.log(zeroes); // [0, 0, 0, 6, 6] zeroes.fill(0); // Reset // Fill elements with an index greater than or equal to 1 and less than 3 with 7 zeroes.fill(7, 1, 3); console.log(zeroes); // [0, 7, 7, 0, 0]; zeroes.fill(0); // Reset // Fill elements with an index greater than or equal to 1 and less than 4 with 8 // (-4 + zeroes.length = 1) // (-1 + zeroes.length = 4) zeroes.fill(8, -4, -1); // Plus the length of the array becomes positive console.log(zeroes); // [0, 8, 8, 8, 0]; fill()Silent ignore index range beyond array boundary, zero length and opposite direction: const zeroes = [0, 0, 0, 0, 0]; // Index too low, ignored zeroes.fill(1, -10, -6); console.log(zeroes); // [0, 0, 0, 0, 0] // Index too high, ignored zeroes.fill(1, 10, 15); console.log(zeroes); // [0, 0, 0, 0, 0] // Index reverse, ignore zeroes.fill(2, 4, 2); console.log(zeroes); // [0, 0, 0, 0, 0] // Index part available, fill in the available part zeroes.fill(4, 3, 10) console.log(zeroes); // [0, 0, 0, 4, 4]
2.copyWithin()
copyWithin() copies parts of the array according to the specified range, and then inserts them at the beginning of the specified index. The start and end indexes are calculated in the same way as fill():
let ints, reset = () => ints = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; reset(); // Copy the contents starting from index 0 from ints and insert them at the beginning of index 5 // Stops when the source or destination index reaches the array boundary ints.copyWithin(5); console.log(ints); // [0, 1, 2, 3, 4, 0, 1, 2, 3, 4] reset(); // Copy the contents starting from index 5 from ints and insert them at the beginning of index 0 ints.copyWithin(0, 5); console.log(ints); // [5, 6, 7, 8, 9, 5, 6, 7, 8, 9] reset(); // Copy contents from index 0 to index 3 in ints // Insert at the beginning of index 4 ints.copyWithin(4, 0, 3); alert(ints); // [0, 1, 2, 3, 0, 1, 2, 7, 8, 9] reset(); // The JavaScript engine completely copies the values in the range before interpolation // Therefore, there is no risk of rewriting during replication ints.copyWithin(2, 0, 6); alert(ints); // [0, 1, 0, 1, 2, 3, 4, 5, 8, 9] reset(); // Negative index values are supported, which is the same as the process of fill() calculating the positive index relative to the end of the array ints.copyWithin(-4, -7, -3); alert(ints); // [0, 1, 2, 3, 4, 5, 3, 4, 5, 6] copyWithin()Silent ignore index range beyond array boundary, zero length and opposite direction: let ints, reset = () => ints = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; reset(); // Index too low, ignored ints.copyWithin(1, -15, -12); alert(ints); // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; reset() // Index too high, ignored ints.copyWithin(1, 12, 15); alert(ints); // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; reset(); // Index reverse, ignore ints.copyWithin(2, 4, 2); alert(ints); // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; reset(); // The index part is available, and the available part is copied and filled ints.copyWithin(4, 7, 10) alert(ints); // [0, 1, 2, 3, 7, 8, 9, 7, 8, 9];
7. Conversion method (toString/valueOf/toLocaleString)
1.toString/valueOf
As mentioned earlier, all objects have toLocaleString(), toString(), and valueof () methods. Among them, valueOf() returns the array itself. toString() returns a comma separated string formed by splicing the equivalent strings of each value in the array. That is, the toString() method is called for each value of the array to get the final string. Look at the following
example:
let colors = ["red", "blue", "green"]; // Create an array of 3 strings alert(colors.toString()); // red,blue,green alert(colors.valueOf()); // red,blue,green alert(colors); // red,blue,green
2.toLocaleString()
The toLocaleString() method may also return the same result as toString() and valueOf(), but not necessarily. When you call the toLocaleString() method of the array, you will get a comma separated string of array values. The only difference between it and the other two methods is that in order to get the final string, the toLocaleString() method of each value of the array is called instead of the toString() method. Take the following example:
let person1 = { toLocaleString() { return "Nikolaos"; }, toString() { return "Nicholas"; } }; let person2 = { toLocaleString() { return "Grigorios"; }, toString() { return "Greg"; } }; let people = [person1, person2]; alert(people); // Nicholas,Greg alert(people.toString()); // Nicholas,Greg alert(people.toLocaleString()); // Nikolaos,Grigorios
Two objects, person1 and person2, are defined here. They both define toString () and toLocaleString() methods and return different values. Then an array of people containing these two objects is created. When passing the array to alert(), the output is "Nicholas,Greg", because the toString() method will be called on each item of the array (the same result as the explicit call to toString() method on the next line). When the toLocaleString() method of the array is called, the result becomes "Nikolaos, Grigorios", which is because the toLocaleString() method of each item of the array is called.
8. Specify symbol split join
The join() method takes a parameter, the string separator, and returns a string containing all items. Consider the following example:
let colors = ["red", "green", "blue"]; alert(colors.join(",")); // red,green,blue alert(colors.join("||")); // red||green||blue
Note that if an item in the array is null or undefined, it will be represented as an empty string in the results returned by join(), toLocaleString(), toString(), and valueOf().
9. Sort / reverse
1.reverse()
let values = [1, 2, 3, 4, 5]; values.reverse(); alert(values); // 5,4,3,2,1
2.sort()
By default, sort() rearranges the array elements in ascending order, that is, the smallest value precedes and the largest value follows. To do this, sort() calls the String() transformation function on each item, and then compares the strings to determine the order. Even if the elements of the array are numeric, the array will be converted into a string first, and then compared and sorted. For example:
let values = [0, 1, 5, 10, 15]; values.sort(); alert(values); // 0,1,10,15,5
At first, the order of the values in the array is correct, but calling sort() will reorder the values in the form of strings. Therefore, even if 5 is less than 10, the string "10" precedes the string "5", so 10 will still come before 5. Obviously, this is not the most appropriate in most cases. To do this, the sort() method can receive a comparison function to determine which value should come first.
The comparison function receives two parameters. If the first parameter should be in front of the second parameter, it returns a negative value; If the two parameters are equal, return 0; Returns a positive value if the first parameter should come after the second. Here is an example of using a simple comparison function:
function compare(value1, value2) { if (value1 < value2) { return -1; } else if (value1 > value2) { return 1; } else { return 0; } }
This comparison function can be applied to most data types. It can be passed as a parameter to the sort() method, as shown below:
let values = [0, 1, 5, 10, 15]; values.sort(compare); alert(values); // 0,1,5,10,15
After passing the comparison function into the sort() method, the values in the array maintain the correct order after sorting. Of course, the comparison function can also produce a descending effect. Just exchange the return values:
function compare(value1, value2) { if (value1 < value2) { return 1; } else if (value1 > value2) { return -1; } else { return 0; } } let values = [0, 1, 5, 10, 15]; values.sort(compare); alert(values); // 15,10,5,1,0
In addition, this comparison function can also be abbreviated as an arrow function:
let values = [0, 1, 5, 10, 15]; values.sort((a, b) => a < b ? 1 : a > b ? -1 : 0); alert(values); // 15,10,5,1,0
Note that both reverse() and sort() return references to the array that called them.
If the element of the array is a numeric value or an object whose valueOf() method returns a numeric value (such as a Date object), the comparison function can also be written more simply, because at this time, you can directly subtract the first value from the second value:
function compare(value1, value2){ return value2 - value1; }
The comparison function is to return values less than 0, 0 and greater than 0, so the subtraction operation can fully meet the requirements.
10. Other operation methods
1. Splice (concat)
The concat() method can create a new array based on all the elements of the existing array. It first creates a copy of the current array, then adds its parameters to the end of the copy, and finally returns the newly constructed array. If you pass in one or more arrays, concat() adds each of these arrays to the result array. If the parameters are not arrays, they are added directly to the end of the result array. Consider the following example:
let colors = ["red", "green", "blue"]; let colors2 = colors.concat("yellow", ["black", "brown"]); console.log(colors); // ["red", "green","blue"] console.log(colors2); // ["red", "green", "blue", "yellow", "black", "brown"]
The behavior of flattening array parameters can be rewritten by specifying a special symbol on the parameter array: symbol isConcatSpreadable. This symbol prevents concat() from flattening the parameter array. On the contrary, setting this value to true can force the flattening of class array objects:
let colors = ["red", "green", "blue"]; let newColors = ["black", "brown"]; let moreNewColors = { [Symbol.isConcatSpreadable]: true, length: 2, 0: "pink", 1: "cyan" }; newColors[Symbol.isConcatSpreadable] = false; // Force not to flatten array let colors2 = colors.concat("yellow", newColors); // Force flattening class array objects let colors3 = colors.concat(moreNewColors); console.log(colors); // ["red", "green", "blue"] console.log(colors2); // ["red", "green", "blue", "yellow", ["black", "brown"]] console.log(colors3); // ["red", "green", "blue", "pink", "cyan"]
2. slice()
- The slice() method is used to create a new array containing one or more elements from the original array
- The slice() method can take one or two parameters: return the start index and end index of the element
- If there is only one parameter, slice() returns all elements indexed to the end of the array
- If there are two parameters, slice() returns all elements corresponding to the start index to the end index, excluding the elements corresponding to the end index. Remember that this operation does not affect the original array
let colors = ["red", "green", "blue", "yellow", "purple"]; let colors2 = colors.slice(1); let colors3 = colors.slice(1, 4); alert(colors2); // green,blue,yellow,purple alert(colors3); // green,blue,yellow
11. Increase
1.splice() add anywhere
There are many ways to use it. The main purpose of splice() is to insert elements in the middle of an array, but there are three different ways to use this method.
1.delete -Need to give splice()Pass 2 parameters: -The location of the first element to delete -Number of elements to delete. Can from Delete any number of elements from the array, such as splice(0, 2)The first two elements are deleted. 2.insert -Need to give splice()Pass three parameters: -Start position -0((number of elements to delete) -Element to insert You can insert an element at a specified position in the array. After the third parameter, you can also pass the fourth and fifth parameters, or even any number of parameters An element to insert. For example, splice(2, 0, "red", "green")The string is inserted starting at position 2 of the array "red"and"green". 3.replace splice()When deleting an element, you can insert a new element at the specified position. Similarly, you need to pass in three parameters: -Start position -Number of elements to delete -Any number of elements to insert. -The number of elements to be inserted is not necessarily the same as the number of elements to be deleted. For example, splice(2, 1, "red", "green")An element is deleted at position 2, and then starts at that position Insert into array"red"and"green".
The splice() method always returns an array containing elements that have been deleted from the array (or an empty array if no elements have been deleted)
let colors = ["red", "green", "blue"]; let removed = colors.splice(0,1); // Delete the first item alert(colors); // green,blue alert(removed); // red, an array with only one element removed = colors.splice(1, 0, "yellow", "orange"); // Insert two elements at position 1 alert(colors); // green,yellow,orange,blue alert(removed); // Empty array removed = colors.splice(1, 1, "red", "purple"); // Insert two values and delete an element alert(colors); // green,red,purple,orange,blue alert(removed);
2. Add the push () stack method to the end
Add an element to the last position of the array:
// Adds an element to the last position of the array // Mode 1: numbers[numbers.length] = 10 // Mode 2: numbers.push(11) numbers.push(12, 13) alert(numbers)
3.unshift() queue method added to header
Of course, we can directly use the unshift method to insert data in the first place of the array
// Insert data in the first place by unshift numbers.unshift(-2) numbers.unshift(-4, -3) alert(numbers) // -4,-3,-2,-1,0,1,2,3,4,5,6,7,8,9,10,11,12,13
12. Delete
1.pop() stack method deletes tail element
If you want to delete the last element of the array, you can use the pop() method
// Delete last element numbers.pop() alert(numbers) // -4,-3,-2,-1,0,1,2,3,4,5,6,7,8,9,10,11,12
2. The shift queue method deletes the first element
numbers.shift() alert(numbers)
3. Delete in any position of splice
The splice() method changes the original array.
Expression arr.splice(index, num, item1, item2,...);
Parameter description
The first parameter is an integer, which is used to specify the position of adding / deleting elements. Negative numbers can be used to start from the tail. Required parameters
The second parameter is the number of elements to be deleted. If you don't want to delete, you can set it to 0, which is optional
The following parameters are optional parameters for the elements added to the array
If it is a delete operation, the deleted elements will be returned in a new array.
1. The element of the operation will include the starting element
2. If there are not enough elements in the array, it will be deleted until the last bit of the array
- Anywhere?
- What we learned earlier is to add and delete data at the beginning and end of the array
- What if we want to do something in the middle of the array?
- On the one hand, we can encapsulate such functions ourselves, but JS has provided us with a splice method
- Delete data through splice
// Delete several elements at the specified location numbers.splice(5, 3) alert(numbers) // -4,-3,-2,-1,0,4,5,6,7,8,9,10,11,12,13
-
Code analysis:
- The above code will delete the elements with indexes 5, 6 and 7
- The first parameter indicates that the starting position of the index is 5 (actually the sixth element, because the index starts from 0), and 3 elements are deleted
What if we want to use splice to insert data?
// Insert element at specified location numbers.splice(5, 0, 3, 2, 1) alert(numbers) // -4,-3,-2,-1,0,3,2,1,4,5,6,7,8,9,10,11,12,13
Code analysis:
- The above code will insert data from the position with index 5 Other data are shifted backward in turn
- The first parameter is still the index value of 5 (the sixth position)
- When the second parameter is 0, it means that the data is not deleted, but inserted
- Followed by the data to be inserted in this position, which can be other types, such as "a", "b", "c"
What if we want to use splice to modify the data?
// Modify the element at the specified location numbers.splice(5, 3, "a", "b", "c") alert(numbers) // -4,-3,-2,-1,0,a,b,c,4,5,6,7,8,9,10,11,12,13
Code analysis:
- The above code will modify the data from the position of index 5. How many? The second parameter
- The first parameter is still the index position of 5 (the sixth position)
- The second parameter is how many elements in the array should be replaced. Here are three (you can also use three elements to replace two, and you can try it yourself)
- Followed by the element to be replaced
13. Change
1.splice
ditto
14. Check
1.indexOf/lastIndexOf/includes
ECMAScript provides two kinds of methods to search arrays: search by strict equality and search by assertion function.
1. Strict equality
ECMAScript provides three strictly equal search methods: indexOf(), lastIndexOf() and includes(). These methods all receive two parameters: the element to find and an optional starting search location
The indexOf() and includes() methods search backwards from the beginning of the array (the first item), while lastIndexOf() searches forwards from the end of the array (the last item).
indexOf() and lastIndexOf() both return the position of the element to be found in the array. If it is not found, it returns - 1. includes() returns a Boolean value indicating whether at least one item matching the specified element was found. When comparing the first parameter with each item of the array, congruent (= = =) comparison will be used, that is, the two items must be strictly equal
let numbers = [1, 2, 3, 4, 5, 4, 3, 2, 1]; alert(numbers.indexOf(4)); // 3 alert(numbers.lastIndexOf(4)); // 5 alert(numbers.includes(4)); // true alert(numbers.indexOf(4, 4)); // 5 alert(numbers.lastIndexOf(4, 4)); // 3 alert(numbers.includes(4, 7)); // false let person = { name: "Nicholas" }; let people = [{ name: "Nicholas" }]; let morePeople = [person]; alert(people.indexOf(person)); // -1 alert(morePeople.indexOf(person)); // 0 alert(people.includes(person)); // false alert(morePeople.includes(person)); // true
2.find/findIndex
2. Assertion function
ECMAScript also allows you to search arrays according to the defined assertion function, which is called for each index. The return value of the assertion function determines whether the elements of the corresponding index are considered to match.
The assertion function receives three parameters: the element, the index, and the array itself. The element is the element currently searched in the array, the index is the index of the current element, and the array is the array being searched. The assertion function returns a true value indicating whether it matches.
The find() and findIndex() methods use assertion functions. Both methods start with the smallest index of the array. find() returns the first matching element, and findIndex() returns the index of the first matching element. Both methods also receive a second optional parameter that specifies the value of this inside the assertion function.
const people = [ { name: "Matt", age: 27 }, { name: "Nicholas", age: 29 } ]; alert(people.find((element, index, array) => element.age < 28)); // {name: "Matt", age: 27} alert(people.findIndex((element, index, array) => element.age < 28)); // 0 When a match is found, neither method will continue the search. const evens = [2, 4, 6]; // When a match is found, the last element of the array is never checked evens.find((element, index, array) => { console.log(element); console.log(index); console.log(array); return element === 4; }); // 2 // 0 // [2, 4, 6] // 4 // 1 // [2, 4, 6]
15. Array to string
1.join
Convert array to string [do not change original array]
The optional parameter is to specify the separator
{ let arr = [1, 2, 3, 4] let b = arr.join('-') console.log(b)//1-2-3-4 console.log(typeof b)//string }
2.toString()
Method converts an array into a string and returns the result. [do not change the original array]
{ let arr = ['xiao', 'hao', 'wen', 24] let b = arr.toString() console.log(b)//xiao,hao,wen,24 }
16. String to array split
Method is used to split a string into an array of strings
- Example 1
In this example, we will split the string in different ways:
<script type="text/javascript"> var str="How are you doing today?" document.write(str.split(" ") + "<br />") document.write(str.split("") + "<br />") document.write(str.split(" ",3)) </script>
Output:
How,are,you,doing,today? H,o,w, ,a,r,e, ,y,o,u, ,d,o,i,n,g, ,t,o,d,a,y,? How,are,you
- Example 2
In this example, we will split strings with more complex structure:
"2:3:4:5".split(":") //Will return ["2", "3", "4", "5"] "|a|b|c".split("|") //Will return ["", "a", "b", "c"]
- Example 3
Using the following code, you can divide a sentence into words:
var words = sentence.split(' ')
Or use regular expressions as separator s:
var words = sentence.split(/\s+/)
- Example 4
If you want to split a word into letters or a string into characters, use the following code:
"hello".split("") //[H "," e "," L "," L "," O "] can be returned
If you only need to return some characters, use the howmany parameter:
"hello".split("", 3) //Can return ["h", "e", "l"]
17. Iterative method
5 iterative methods
Receive three parameters: array element, element index and array itself
The function that runs with each item as a parameter, and the optional scope object as the function running context (affecting the value of this in the function).
None of these methods change the array that calls them.
every(): Run the passed in function for each item of the array. If the function returns for each item true,Then this method returns true. filter(): Run the passed in function on each item of the array, and the function returns true The items are returned as an array. forEach(): Run the passed in function on each item of the array without returning a value. map(): Run the passed in function on each item of the array and return an array composed of the results of each function call. some(): Run the passed in function for each item of the array. If one item returns true,Then this method returns true.
1. every() method
Check whether all the elements in the array meet the conditions
-
The every() method passes every element in the array into a function that returns true/false
-
If each element in the function returns true, the result will be true. If one element is false, the result will be false
-
Every exercise:
- Determine whether a group of elements contains a character
// Define array var names = ["abc", "cb", "mba", "dna"] // Determine whether the elements of the array contain the a character var flag = names.every(function (t) { return t.indexOf('a') != -1 }) alert(flag)
2. some() method
some() detects whether there are elements in the array that meet the conditions
Syntax arr.some(function(value, index, arr), this);
The parameter value is the same as forEach
Return value: Boolean type: true / false
-
The some() method passes each element in the array into a function that returns true/false
-
But unlike every, once a function returns true, the iteration ends And the result is true
-
some() exercise
// Define array var names = ["abc", "cb", "mba", "dna"] // Determine whether the array contains a character var flag = names.some(function (t) { alert(t) return t.indexOf("a") != -1 }) alert(flag)
3. filter() method
Filter the original array and return the new array
- The filter() method is a filter function
- First, each element in the array will be traversed and passed into the function
- If the result of the function returns true, this element will be added to the latest array. If it returns false, this element will be ignored
- Finally, a new array will be formed, which is the return value of the filter() method
// Define array var names = ["abc", "cb", "mba", "dna"] // Gets all elements in names that contain the 'a' character var newNames = names.filter(function (t) { return t.indexOf("a") != -1 }) console.log(newNames)//abc,mba,dna
4.map() method
Process each element in the array and return a new array
- The map() method provides a mapping function
- First, it will traverse each element in the array and pass it into the function
- The element will undergo various transformations through the instructions in the function to generate a new element and return the new element
- Finally, all the returned elements will form a new array, which is the return value of the map() method
- map() exercise:
// Define array var names = ["abc", "cb", "mba", "dna"] // Splice - abc after all elements in names var newNames = names.map(function (t) { return t + "-abc" }) alert(newNames)
5. forEach() method
The forEach() method is just a quick way to iterate over an array This method does not need to return a value and traverses the array in ascending order
Syntax:
arr.forEach(function(value, index, arr), this);
Value (required): the array value at the time of current traversal.
Index (optional): the index value during the current traversal.
Arr (optional): the array object itself.
This (optional): when the callback function is executed.
Use of forEach
// Define array var names = ["abc", "cb", "mba", "dna"] // Use of forEach names.forEach(function (t) { alert(t) }) let arr = [1, 2, 3, 4, 5, 6] arr.forEach((value, index) => { console.log(`${index}:${value}\n`)//value })
18. Consolidation method
ECMAScript provides two merging methods for arrays: reduce() and reduceRight(). Both methods iterate over all the items of the array and build a final return value on that basis. The reduce () method starts from the first item of the array and traverses to the last item. Reducereight() starts from the last item and traverses to the first item.
1. reduce method
Syntax: arr.reduce((total, value, index, arr), init)
Parameter Total (required): the initial value, followed by the return value of the previous callback.
Value (required): the value of an array element.
Index (optional): index value.
Arr (optional): array object.
Init (optional): initial value.
Return value: the accumulated value
The accumulator of the array is merged into one value.
-
We take out the reduce method alone, because this method is relatively difficult to understand
-
First, let's look at the parameters required by this method:
arr.reduce(callback[, initialValue])
parameter
-
callback (a function called on each item in the array, which accepts four parameters:)
- previousValue (return value or initial value when the callback function was last called)
- currentValue (array element currently being processed)
- currentIndex (index of array element currently being processed)
- Array (the array that calls the reduce() method)
-
initialValue (optional initial value. As the value passed to previousValue when the callback function is called for the first time)
-
Some are obscure. Let's look at the examples directly
- Find the cumulative sum of numbers in a number
Use for to implement:
// 1. Define array var numbers = [1, 2, 3, 4] // 2.for realize accumulation var total = 0 for (var i = 0; i < numbers.length; i++) { total += numbers[i] } alert(total) // 10
Simplify the for loop with forEach
- Compared with the for loop, forEach is more in line with our thinking (traversing the elements in the array)
// 3. Use forEach var total = 0 numbers.forEach(function (t) { total += t }) alert(total)
Using reduce method
// 4. Use the reduce method var total = numbers.reduce(function (pre, cur) { return pre + cur }) alert(total)
Code analysis:
- The parameters passed in each time in pre are not fixed, but the results of the last function execution are saved in pre
- For the first execution, pre is 0 and cur is 1
- In the second execution, pre is 1 (0 + 1, the result of the last function execution) and cur is 2
- In the third execution, pre is 3 (1 + 2, the result of the last function execution) and cur is 3
- In the fourth execution, pre is 6 (3 + 3, the result of the last function execution) and cur is 4
- When cur is 4, the elements in the array are traversed, and the result of the fourth time is directly returned as the return value of the reduce function
Doesn't seem to have much advantage over forEach?
-
Through this code, you will find that you do not need to define a variable before calling the function, but only need a variable to receive the final parameters of the method
-
But is that the advantage? No, the advantage is that the reduce method has a return value, while forEach does not
-
What's the advantage? If the reduce method has a return value, the reduce method itself can be passed as a parameter directly to another function that needs the return value of reduce as a parameter In forEach, you can only save the result of each function in a variable, and then pass the variable into the parameter
-
Yes, this is the very popular functional programming recently It is also the reason that almost every language that can use functional programming has the method of reduce
-
Functional programming is not discussed in this course. I just saw this function and extended it to you (I will have the opportunity to share functional programming with you later)
-
initialValue
- In fact, it is the value of pre when the function in reduce is executed for the first time
- Because the default pre is 0.0 when it is first executed