This is the 13th day of my participation in the August More Text Challenge.More challenges in August

Create array one

The Array type is also a fairly common type in JavaScript. And arrays in JavaScript are very different from arrays in other languages. Although arrays in JS are ordered lists like arrays in other languages, unlike arrays in other languages, each item in an array in JS can hold any type of data. That is, the first value of an array can be a string, the second value can be a number, the third value can be a Boolean, an object, and so on. And the JS array can be dynamically resized.

There are two basic ways to create arrays. The first is to use the Array constructor, as follows:

var colors = new Array(a);Copy the code

If you know the number of items to hold in the array in advance, you can pass that number to the constructor, which is automatically changed to the value of the Length property, the length of the array. Look at the following example:

var colors = new Array(20);// Create an array of length 20
Copy the code

We can also pass specific items from the Array to the Array constructor, as follows:

var colors = new Array('red'.'pink'.'green');// Create an array of three values
Copy the code

Be careful when passing only one argument to the constructor, because if the argument is a number, an array containing the given number of items is created from that number, which becomes the length value of the array. If other types of arguments are passed, an array of length 1 containing the value is created. The following is an example:

var colors = new Array(3); // An empty array of length 3
var names = new Array("Alvin");// An array of length 1 containing the value Alvin
Copy the code

Alternatively, you can omit the new keyword when using the Array constructor, as shown below. Omitting the new keyword yields the same result:

var colors = Array(3); // An empty array of length 3
var names = Array("Alvin");// An array of length 1 containing the value Alvin
Copy the code

Create array two

The second basic way to create an array is to use array literal notation. Array literals are represented by a pair of square brackets containing the array values, separated by commas, as shown below:

var colors = ['red'.'pink'.'green']; // Create an array of three strings
var names = []; // Create an empty array
Copy the code

The above code creates an array of three strings of length and an empty array, respectively.

When reading and setting array values, access or setting is done using square brackets and subscripts, starting at 0. Consider the following example:

var colors = ['red'.'pink'.'green'];
console.log(colors[1]); //pink

colors[0] = 'yellow'; // Update the first element to yellow
colors[3] = 'blue';// Add a new value blue
Copy the code

The index in square brackets indicates the value to be accessed. If the index is smaller than the length of the array, the value of the corresponding index is returned. In this example colors[0] returns’ red ‘. Setting the value of the array is the same, but replaces the original value of the specified index position. If you set an index to a value that exceeds the length of the array, such as colors[3], the array is automatically increased to the length of that index plus 1. The length of the array is stored in the Length attribute, which always returns a value of 0 or greater. The following code looks like this:

var colors = ['red'.'pink'.'green'];
var names = [];

console.log(colors.length);/ / 3
console.log(names.length); / / 0
Copy the code

The length property of the array is unique in that it is not read-only, so you can set this property to remove or add items from the end of the array

var colors = ['red'.'pink'.'green']; // Create an array of length 3
colors.length = 2; // Set the array length to 2
console.log(colors[2]);//undefined
Copy the code

In the code snippet above, we changed the length of the array to 2 and found that the third value of the array becomes undefined. If its length property is set to a value greater than the number of items in the array, each new item takes undefined.

To determine whether an object is an Array, use array.isarray (obj). Such as:

var colors = ['red'.'pink'.'green'];
console.log(Array.isArray(colors));// true
Copy the code

Conversion method

toLocaleString()

toString()

valueOf()

When we talked about the Object type, we already mentioned that all objects have toLocaleString(), toString(), and valueOf() methods. The toString() method that calls the array returns a comma-separated string concatenated from the string form of each value in the array. To further understand, let’s take a look at the following example:

var colors = ['red'.'pink'.'green'];
console.log(colors.toString()); // "red,pink,green"
console.log(colors.valueOf()); // "red,pink,green"
console.log(colors); // "red,pink,green"
Copy the code

In the above code, the toString() and valueOf() methods are called first, which returns a comma-separated string of string forms for each value. The last line passes the array directly to console.log(), and since console.log() receives string arguments, it calls the toString() method behind the scenes, which gives the same result as if it had called the toString() method. We can also use the join() method to achieve the same effect, except that we can call the join() method to specify a different delimiter, as shown below:

var colors = ['red'.'pink'.'green'];
console.log(colors.join(', ')); //"red,pink,green"
console.log(colors.join('| |')); // "red||pink||green"
Copy the code

The stack method

Push () is added from the end of the array

Pop () is removed from end of array

JavaScript arrays also provide a way to make arrays behave like other data structures. In particular, arrays can behave like stacks. A stack is a data structure that restricts insertion and deletion. The stack is a last-in-first-out (LIFO) data structure, where the Last item added is removed First. The insertion and removal of items in the stack (also called push and eject) occurs in only one place — at the top of the stack. JavaScript provides push() and pop() methods specifically for arrays to implement stack-like behavior.

The push() method can take any number of arguments, append them one by one to the end of the array, and return the length of the modified array. The pop() method, on the other hand, removes the last item from the end of the array, reducing the array’s length, and returns the removed item.

var colors = []; // Define an empty array
var len = colors.push("red"."pink");// Push two items red and pink into the array and return the new length of the array
console.log(len); / / 2

len = colors.push('green'); // Add a new value green
console.log(len); // The new length of the array is 3


var item = colors.pop();
console.log(item); // Green removes the last item of the array and returns
console.log(colors.length); // The array length becomes 2
Copy the code

The array in the above code can be thought of as a stack, with push and pop being the default array methods. First we call push() to push two strings to the end of the array and store the returned result (the length of the array) in a variable. Then we push a new value. The result is still stored in the variable, and the array is 3 in length. When the pop method is called, it returns the last item of the array, the string green, at which point the length of the array becomes 2.

It is also possible to combine stack methods with other array methods, such as:

var colors = ['red'.'pink']; // Create an array of length 2 with the values red and pink

colors.push("green");// Add a new value green to the array using the push method
colors[3] = 'blue'; // Add a new value blue to the array by subscript

console.log(colors.length); //4 The array length changes to 4

var item = colors.pop(); // Remove the last item in the array blue
console.log(item);/ / return to blue
Copy the code

Queue method

Shift () is removed from the front of the array

Unshift () is added from the front of the array

Stack data structures have LIFO (last In, First Out) access rules, while queue data structures have FIOF (first-in-first-out) access rules. Queues add items at the end of the list and remove items at the front of the list. Because push is a method that adds items to the end of an array, all you need to simulate queuing is a method that gets items from the front of the array. Arrays also provide a method — shift() — that removes the first item in the array and returns that item, while reducing the array length by one. Take a look at the following code:

var colors = []; // Create an empty array
var len = colors.push('red'.'pink');// Push red and pink into the array
console.log(len); // The array length becomes 2

len = colors.push('green'); // Add green and the array length becomes 3

var item = colors.shift();// Removes the value of the first item in the array and returns it
console.log(item);// red
console.log(colors.length); //2 array length is 2 again
Copy the code

In the example above, we add three values (red, pink, green) to the array by calling the array’s push method. Then we call the array’s Shift () method to remove the first value from the array and return it to the variable item. This confirms that shift() removes from the front of the array, as opposed to pop().

JavaScript also provides an unshift() method for arrays. As the name suggests, unshift() does the opposite of shift() : it adds any item to the front of the array and returns the length of the new array. So we can use the unshift() and pop() methods to simulate queuing from the opposite direction, adding items to the front of the array and removing items from the end of the array, as follows:

var colors = [];
var len = colors.unshift('red'.'green');
console.log(len); / / 2

len = colors.unshift('pink');

var item = colors.pop();
console.log(item);// green
Copy the code

In the above code, because the values are pushed in from the front, the last pushed pink becomes the first item in the array, and green becomes the last item, so we get green by calling pop().

Reorder method

The reverse () inversion

There are two methods for sorting arrays in JavaScript: the reverse() and sort() methods. The Reverse method reverses the items of the array. As follows:

var values = [1.2.3.4.5];
values.reverse();
console.log(values);// output 5,4,3,2,1
Copy the code

Here the initial values of the array are 1,2,3,4,5. When the reverse() method is called, the order of values changes to 5,4,3,2,1. It is clear that the order of the items has been reversed.

Sort () sort

The other method, sort(), sorts the items in ascending order. To sort, sort calls the toString() method of each item and compares the resulting strings to determine how to sort. Even if every item in the array is a numeric value, sort still compares strings.

var values = [0.1.5.10.15];
values.sort();
console.log(values);/ / 0,1,10,15,5
Copy the code

As you can see, even if the order of the values in the array is fine, the sort() method changes the original order based on the result of the string. Because the value 5 is less than 10, “10” comes before “5” in string comparisons, the order of the array is changed. Obviously this sort of sorting is not optimal in many cases. So the sort method can take a comparison function as an argument so that we can specify which value comes before which.

The comparison function takes two arguments and returns a negative number if the first argument should come before the second, 0 if the two arguments are equal, and a positive number if the first argument comes after the second. The comparison function works for most data types, as long as you take it as an argument to the sort method. Look at the following code:

function compare(value1, value2){
    if(value1 < value2){
        return -1;
    }else if(value1 > value2){
        return 1;
    }else{
        return 0; }}var values = [0.5.1.15.10];
values.sort(compare);
console.log(values);/ / 0,1,5,10,15
Copy the code

Now we see that the order of the array is sorted by the size of the value. So if you want to sort in descending order, just swap the return values of value1 and value2.

function compare(value1, value2){
    if(value1 < value2){
        return 1;
    }else if(value1 > value2){
        return -1;
    }else{
        return 0; }}var values = [0.5.1.15.10];
values.sort(compare);
console.log(values);/ / 15,10,5,1,0
Copy the code

Tips: The reverse() and sort() methods return a sorted array.

For a numeric type or an object type whose valueOf method returns a numeric type, you can use a simpler comparison function that simply subtracts the first argument from the second argument, as shown in the following code:

function compare(value1, value2){
    return value2 - value1;
}
Copy the code

Operation method

Concat () joining together

JavaScript provides many methods for manipulating items in arrays, among which the concat() method creates a new array based on all the items in the current array. Specifically, this method creates a copy of the current array, appends the received arguments to the end of the copy, and returns the newly constructed array. Without passing arguments to the concat method, it simply copies the current array and returns a copy. If the concat method is passed one or more arrays, it adds each of those arrays to the result array. If it is not passed an array, the values are simply added to the end of the result array. Take a look at the following code:

var colors = ['red'.'green'.'pink'];
var colors2 = colors.concat('yellow'['black'.'blue']);

console.log(colors); //red,green,pink
console.log(colors2); //red,green,pink,yellow,black,blue
Copy the code

From the above code, it is not difficult to see that the new array colors2 is added with new elements yellow, black and blue on the basis of the original array colors. Yellow is added to the new array in the form of string, while black and blue are concat to the new array in the form of array.

The slice () intercept

The other method is slice(), which creates a new array based on one or more items in the current array. The slice() method can take one or two arguments to return the start and end positions of the item. In the case of a single argument, the slice() method returns all items from the position specified by that argument to the end of the current array. If there are two arguments, the method returns the items between the start and end positions, but not the items at the end position. Note here that the slice() method does not affect the original array. Look at the following example:

var colors = ['red'.'green'.'blue'.'yellow'.'pink'];
var colors2 = colors.slice(1);
var colors3 = colors.slice(1.4);

console.log(colors2);//green,blue,yellow,pink
console.log(colors3);//green,blue,yellow
Copy the code

In the above code, we create a colors array with 5 colors. Then we call the array’s slice method and pass in a parameter 1, which means that we slice from the second item of the array with index 1 to the end of the array. Green, blue, yellow and pink. In the third line of code, we also call the slice method for colors, but this time we pass two parameters, 1 and 4, which means that we intercept from the item with index 1 to the item with index 4 (but not including the item with index 4), so we get the value of colors3: Green, blue and yellow.

Splice () deletes/inserts/replaces

One of the more powerful methods in arrays is the splice() method, which has several uses, as follows:

  • Delete: You can delete any number of items in the array by passing only two arguments: the location of the item to be deleted (index) and the number of items to be deleted. For example, splice(1,2) deletes two items starting with index 1 in the array. Note: The second argument here is not the end position but the number of items to delete.
  • Insert: Any number of items can be inserted into the specified location, and three or more arguments are required: for the location to be inserted, the second argument must be passed 0 (because, as described above, the second argument represents the number of items to be deleted, which is not deleted), and the third argument is the item to be inserted. You can pass in a fourth term, a fifth term, any number of them. For example, splice(2,0,’black’, ‘grey’) inserts black and grey from the second position in the current array.
  • Substitution: In fact, substitution is very similar to the previous insert, except that the second argument is changed to a specific number of terms, that is, delete first and then insert. You can insert any number of items into a specified location and delete any number of items at the same time. Again, you need to provide three parameters: the starting location, the number of items to delete, and the number of items to insert, where the number of items to insert and the number of items to delete need not be equal. For example, splice(2,1,’red’, ‘green’) deletes two items from the array and inserts red and green from index 2

The splice method always returns an array containing the items deleted from the original array (or an empty array if no items are deleted). Consider the following code, which shows the use of the above three methods:

/ / delete
var colors = ['red'.'green'.'pink'];
var removed = colors.splice(0.1);// Delete the first item
console.log(colors); //green,pink
console.log(removed);//red

/ / insert
removed = colors.splice(1.0.'yellow'.'orange');// Insert two values from index 1
console.log(colors);//green,yellow,orange,pink
console.log(removed);// Returns an empty array

/ / replace
removed = colors.splice(1.1.'red'.'blue');// Delete one value from index 1 and insert two values
console.log(colors);//green,red,blue,orange,pink
console.log(removed);//yellow
Copy the code

Location method

indexOf()

lastIndexOf()

Es5 provides two positional methods for arrays, indexOf() and lastIndexOf(). Both methods take two parameters: the item to look for and the index representing the starting point of the search. IndexOf() looks backwards from the beginning of the array (index 0), while lastIndexOf() looks forwards from the end of the array.

Both methods return the position of the item in the array, or -1 if it is not found. When comparing the first argument with each item in the array, the congruence operator is used, which means that the items to be looked for must be exactly equal (just as with ===). Take a look at the following example:

var nums = [1.2.3.4.5.4.3.2.1];

// look backwards from 0 to return the index
console.log(nums.indexOf(4));/ / 3
// Look forward from the last item
console.log(nums.lastIndexOf(4));/ / 5

// Look backwards from index 4
console.log(nums.indexOf(4.4));/ / 5
// look forward from index 4
console.log(nums.lastIndexOf(4.4));/ / 3


var person = {name: 'Alvin'};
var people = [{name:'Alvin'}];

var morePeople = [person];
console.log(people.indexOf(person));/ / 1
console.log(morePeople.indexOf(person));/ / 0
Copy the code

An iterative approach

Es5 provides five iterating methods for arrays. Each method takes two arguments: the function to run on each item and, optionally, the scoped object that runs the function — which affects the value of this. The functions passed into these methods take three arguments: the value of the array item, the item’s index in the array, and the array object itself.

filter()

Returns an array of items that return true by running the given function on each item in the array. For example, return an array where all values are greater than 2.

var nums = [1.2.3.4.5.4.3.2.1];

var res = nums.filter(function(value,index,arr){
    return value > 2;
});

console.log(res);/ /,4,5,4,3 [3]
Copy the code

forEach()

Runs the given function on each item in the array, with no return value. Essentially the same as iterating through an array with a for loop. Such as:

var nums = [1.2.3.4.5.4.3.2.1];

nums.forEach(function(value,index,arr){
    // Perform some operations
});
Copy the code

map()

Run the given function on each item in the array, returning an array of the results of each function call. For example, multiply each item in an array by 2, and return the array with each item multiplied.

var nums = [1.2.3.4.5.4.3.2.1];

var res = nums.map(function(value,index,arr){
    return value * 2;
});

console.log(res);/ /,4,6,8,10,8,6,4,2 [2]
Copy the code

every()

Executes the given function on each item in the array, returning true if the function returns true for each item.

var nums = [1.2.3.4.5.4.3.2.1];

var every = nums.every(function(value,index,arr){
    return value > 2;
});

console.log(every); //false
Copy the code

some()

Run the given function on each item in the array, returning true if the function returns true for any item.

var nums = [1.2.3.4.5.4.3.2.1];

var every = nums.some(function(value,index,arr){
    return value > 2;
});

console.log(every); //true
Copy the code

None of the above methods modify the values contained in the array. The most similar of these methods are every() and some(), which are used to check whether items in an array meet certain conditions. For every(), the passed function must return true for each item, and false otherwise. The some() method, on the other hand, returns true whenever the function passed in returns true for an item in the array.

Return value summary

  • Filter () returns a new array of items that match the criteria, such as those greater than 2
  • Map () returns the array of operations performed on the items, such as multiplying each item by 2
  • ForEach () works like a for loop, with no return value
  • Every () returns only true or false
  • Some () only returns true or false

Narrow method

reduce()

reduceRight()

Es5 also provides two methods to shrink arrays: reduce() and reduceRight(). Both methods iterate over all the items in the array and then build a final return value. Where reduce method starts from the first item of the array and traverses to the end one by one, while reduceRight starts from the last item of the array and traverses forward to the first item.

Both methods accept two parameters: a function called on each item and an optional initial value as a basis for narrowing. The function passed to these two methods takes four parameters: the previous value, the current value, the item’s index, and the array object. Any value returned by this function is automatically passed to the next item as the first argument. The first iteration occurs on the second item of the array, so the first argument is the first item of the array, and the second argument is the second item of the array.

The reduce() method performs operations that evaluate the sum of all the values in an array, such as:

var values = [1.2.3.4.5];

var sum = values.reduce(function(prev,cur,index,arr){
    return prev + cur;
});

console.log(sum);/ / 15
Copy the code

The first time the callback is executed, prev is 1 and cur is 2. The second time, perv is 3 (the result of 1 plus 2) and cur is 3 (the third item in the array). This process continues until each item in the array has been accessed and the result is returned.

ReduceRight works in just the opposite direction.

var values = [1.2.3.4.5];

var sum = values.reduceRight(function(prev,cur,index,arr){
    return prev + cur;
});

console.log(sum);/ / 15
Copy the code

In this example, the first time the callback is executed, prev is 5 (the last item in the array) and cur is 4 (the second-to-last item). The end result is the same.

Whether you use Reduce or reduceRight, it mainly depends on which side to start traversing the number groups, otherwise they are completely the same.

So those are some of the ways you can manipulate arrays in JavaScript.