This is the 21st day of my participation in the August Text Challenge.More challenges in August

These methods are more commonly used in actual development, and I finally sorted them out

Conversion method

toLocaleString()&toString()&valueOf()

All objects have toLocaleString(), toString(), and valueOf() methods; Among them,

  • valueOf()Return orAn array ofItself;
  • toString()Returns a comma-delimited concatenation of equivalent strings for each value in the arraystring;
  • That is, it is called for each value of the arraytoSting()Method to get the final string.
let colors = ["red"."blue"."green"];
console.log(colors.toString());
console.log(colors.valueOf());
console.log(colors.toLocaleString());
Copy the code

The following output is displayed:

tolocaleString()Method may return the followingtoString()andvalueOf()The same result might be a string of comma-separated array values. The only difference from the other two methods is that each value of the array is calledtolocaleString()Method, rather thantoString(); So what’s the difference between the two? Take a look at the following code and its printout, for example:

const date = new Date(a);console.log(date.toString());
console.log(date.toLocaleString());
const number = 8888.88;
console.log(number.toString());
console.log(number.toLocaleString());
Copy the code

The following output is displayed:

join()

If you want to use a different delimiter, use the join() method; The join() method takes one argument, a string delimiter, and returns a string containing all items.

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

If an item in the array is null or undefined, the result returned in the above four methods is represented as an empty string.

Stack and queue methods

  • Insert from the end of the arraypush()Method, delete/remove usepop()Methods;
  • Used by pushing from the array headerunshift()Method, derived useshift()methods
let colors = ["red"."blue"."green"];
colors.push('pink');   // ["red", "blue", "green", "pink"]
Copy the code

These functions are different and used similarly;

Sorting method

Arrays have two methods for reordering elements: reverse() and sort();

sort()

By default, sort() rearranges array elements in ascending order, with the smallest value in front and the largest value behind; Sort () calls the String() transformation function on each item and compares the strings to determine the order. Even if all the elements in the array are numeric, the array is converted to a string before comparison and sorting.

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

The problem with sort is that strings are compared from the first digit, such as string “10” before string “5”. So, most of the time, we pass a comparison function to sort() to determine which value should come first.

reverse()

This method starts by arranging the elements of the array in the right direction.

Operation Method [Common]

concat()

  • You can create a new array based on all the elements of an existing array.
  • If one or more arrays are passedconcat()Each of these arrays is added to the result array.
  • If the parameters are not arrays, they are appended directly to the end of the result array.

When using the concat() method, the array is flattened by default. Look at the output of this code:

let color = ["red"];
console.log(color.concat("yellow"["black"."pink"]));
Copy the code

The behavior of flattening array parameters can be rewritten by specifying a special Symbol on the array of parameters: symbol.isconcat-spreadable. Setting this symbol to false prevents concat() from flattening the array. Such as: color [Symbol isConcatSpreadable] = flase

slice()

Use to create a new array containing one or more elements of the original array. The slice() method can take one or two arguments; Returns the start and end index of the element.

  • If there is only one argument, return all elements of the index to the end of the array

  • If there are two arguments, all elements corresponding to the start index to the end index are returned, excluding the elements corresponding to the end index

    let colors = ["red"."blue"."green"."pink"];
    console.log(colors.slice(1));  // ["blue", "green", "pink"]
    console.log(colors.slice(1.3));  //["blue", "green"]
    Copy the code

If the slice() argument has a negative value, the location of the copy is determined by the numeric length. For example, calling slice(-2, -1) on a 5-element array is equivalent to calling slice(3, 4); If the start position is greater than the end position, an empty array is returned.

splice()

This method is very powerful and is mainly used to insert elements in the middle of an array

  • delete. tosplice()Pass in two arguments:The first element to be deleted and the number of elements to be deleted. You can delete any number of elements from an array, for examplesplice(0, 2)The first two elements are removed.
  • insert. tosplice()Pass in three arguments:The starting position, 0(number of elements to delete), and the element to insert, starting with the third parameter, the following parameters are the parameters to be inserted; For instance,splice(2, 0, 'pink', 'blue'), inserts strings starting at array position 2'pink' and 'blue'.
  • replace.spliceTo delete an element, you can insert a new element at the specified location, again passing three arguments:The starting position, the number of elements to delete, and any number of elements to insert

Search and location methods

1. Strict equality

indexOf()&includes()&lastIndexOf()

  • indexOf()andincludes()Method starts at the front of the array (the first item) and searches backwards, whilelastIndexOf()Search forward from the end of the array (the last item).
  • includes()&lastIndexOf()Methods all return valuesLocate the element in the arrayIf not found, -1 is returned.includes()returnBoolean value, indicating whether at least one item matching the specified element was found.
  • When comparing the first parameter with each item in the array, we use congruence (===), which means that the two items must be exactly equal

2. Assert functions

The assertion function takes three arguments: the element, index, and array itself; The find() and findIndex() methods use assertion functions;

find()&findIndex()

  • find()Returns the first matched element
  • findIndex()Returns the index of the first matched element
const arr = [{name:'mannqo'.age:18}, {name:'yt'.age:12}]
console.log(people.find(element, index, array) => {element.age<16});  //{name:'yt', age:12}
console.log(people.findIndex(element, index, array) => {element.age<16});   / / 0
Copy the code

Iterative method [most commonly used]

An array of five iterating methods, each of which takes two arguments: a function to run as an argument for each item, and an optional scoped object that serves as the context in which the function is run (affecting the value of this in the function). The function passed to each method takes three arguments: the element of the array, the element index, and the array itself, and runs the passed function on each entry of the array.

  • everyThis method returns true if it returns true for every function
  • someThis method returns true if one of the functions returns true
  • filterThe: function returns true and returns an array of items
  • forEach: Returns no value, equivalent to iterating through the array using the for loop
  • map: returns an array of the results of each function call

Merge method

reduce()&reduceRight()

Both methods take two parameters: a merge function that runs for each item, and an optional initial value that is the starting point for the merge. The function passed to reduce()&reduceRight() takes four arguments: the last merge value, the current item, the index of the current item, and the array itself.

  • reduce()Method iterates from the first item in the array to the last
  • reduceRight()The method traverses from the last item to the first line
let arr = [1.2.3.4.5];
console.log(arr.reduce((pre, cur, index, arr) = > pre + cur));
Copy the code

The difference between these two methods lies in the different directions of traversal;