What are the common methods for manipulating array elements?

1. Copy and fill

② Fill the array: fill()

Insert all or part of the same values ​​into an existing array. The syntax of this method is as follows: 

array.fill(value, start, end)

  • value : required. filled value;
  • start: optional. Start filling position (default 0);
  • end: optional. Stop filling position (default is array.length to fill to the end of the array )

Fill the array with a from the second to the fifth position: 

      let arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
      arr.fill("a", 2, 5);
      console.log(arr); // [0, 1, 'a','a', 'a', 5, 6, 7, 8, 9];
      const arr = [0, 0, 0, 0, 0];

      // 用5填充整个数组
      arr.fill(5);
      console.log(arr); // [5, 5, 5, 5, 5]
      arr.fill(0); // 重置

      // 用5填充索引大于等于3的元素
      arr.fill(5, 3);
      console.log(arr); // [0, 0, 0, 5, 5]
      arr.fill(0); // 重置

      // 用5填充索引大于等于1且小于等于3的元素
      arr.fill(5, 1, 4);
      console.log(arr); // [0, 5, 5, 5, 0]
      arr.fill(0); // 重置

      // 用5填充索引大于等于-1的元素
      arr.fill(5, -1);
      console.log(arr); // [0, 0, 0, 0, 5]
      arr.fill(0); // 重置
② Batch copy: copyWithin()

Shallowly copies part of the array content according to the specified range, and then inserts it at the starting position of the specified index . The starting and ending indexes are calculated in the same way as the fill method. The syntax of this method is as follows:

array.copyWithin(target, start, end)

Its parameters are as follows:

  • target : required. Copy to the specified target index location;
  • start: optional. The starting position of element copy;
  • end: optional. The index position to stop copying (defaults to  array .length). If it is a negative value, it represents the reciprocal value.

Copy  the elements starting at the start  position and the elements between the end  position to the first position of the array. 

      const array1 = [1, 2, 3, 4, 5];
      console.log(array1.copyWithin(0, 3)); // [4, 5, 3, 4, 5]

      const array2 = [1, 2, 3, 4];
      console.log(array2.copyWithin(0, 3)); //  [4, 2, 3, 4]

      const array3 = [1, 2, 3, 4, 5, 6, 7, 8];
      console.log(array3.copyWithin(0, 3)); //  [4, 5, 6, 7, 8, 6, 7, 8]

      const array4 = [1, 2, 3, 4, 5, 6, 7, 8];
      console.log(array4.copyWithin(0, 3, 5)); //  [4, 5, 3, 4, 5, 6, 7, 8]

The signatures of these two methods are similar. They both need to specify a range on the existing array instance, including the starting index and not including the ending index.

 

2. Conversion method

There are four main methods for converting arrays: toLocaleString(), toString(), valueOf(), join()

It should be noted that if an item in the array is null or undefined, the returned result will be represented by an empty string after calling the first three methods.

① toString()

What is returned is a comma-separated string concatenated by the equivalent string of each value in the array. That is to say, each value in the array will call the toString() method to get the final string.

let colors = ["red", "blue", "green"];  
console.log(colors.toString())  // red,blue,green

let array = [{ name: "zz" }, 123, "abc", new Date(), [1, 2]];
console.log(array.toString()); // [object Object],123,abc,Fri Nov 10 2023 22:18:25 GMT+0800 (中国标准时间),1,2
② valueOf()

What is returned is the array itself

      let colors = ["red", "blue", "green"];
      console.log(colors.valueOf()); // ["red", "blue", "green"]
③ toLocaleString()

The toLocaleString() method may return the same result as the toString() method, but not necessarily.

When you call the toLocaleString() method, you will get a string of comma-separated array values. The difference from the toString() method is that in order to get the final string, the toLocaleString() method of each value will be called instead of toString. ()method

      let array = [{ name: "zz" }, 123, "abc", new Date()];
      let str = array.toLocaleString();
      console.log(str); // [object Object],123,abc,2016/1/5 下午1:06:23
④ join()

Put all elements in the array into a string. Elements are separated by the specified delimiter, which defaults to commas.

This method returns a string. The string is generated by converting each element in the array to a string and then concatenating the strings, inserting the separator string between the two elements. 

let array = ["one", "two", "three","four", "five"];
console.log(array.join());      // one,two,three,four,five
console.log(array.join("-"));   // one-two-three-four-five

 

3. Stack method

The stack is a last-in-first-out structure , that is, the most recently added items are deleted first.

The insertion (called push) and deletion (called pop) of data items only occur at the top of the stack.

① push()

Receives any number of arguments, appends them to the end of the array, and returns the new length of the array. This method will change the original array. Its grammatical form is as follows:

arrayObject.push(newelement1, newelement2, ...., newelementX)

      let array = ["1", "2",  "3"];
      array.push("4", "5", "6")
      let i = array.push("666");
      console.log(array); // ["1", "2", "3", "4"]
      console.log(i); // 7
② pop()

Removes and returns the last element of an array. It has no parameters. This method will change the original array.

      let array = ["1", "2", "3"];
      let i = array.pop();
      console.log(array); // ["1", "2"]
      console.log(i); // 3

 

4. Queue method

The queue is a first-in-first-out data structure . The queue adds elements at the end of the queue and deletes elements at the opposite end.

Methods to remove and add elements from the beginning of an array: shift() and unshift()

① shift()

Removes the first item from an array and returns the removed element. Then the length of the array is reduced by one, and this method will change the original array.

Note: If the array is empty, the shift() method will do nothing and return an undefined value. 

      let array = ["1", "2", "3"];
      let i = array.shift();
      console.log(array); // ["2", "3"]
      console.log(i); // 1
② unshift()

Adds one or more elements to the beginning of the array and returns the new length. This method will change the original array.

arrayObject.unshift(newelement1,newelement2,....,newelementX)

      let array = ["1", "2", "3"];
      let i = array.unshift('111', '222', '333');
      console.log(array); // ["111", "222", "333", "1", "2", "3"]
      console.log(i); // 6

 

5. Sorting method

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

① sort()

Array sorting sort() method_Little Strawberry Jumping Blog-CSDN Blog 

This method will sort the original array and change the original array.

 arrayObject.sort(sortby)

The parameter sortby is an optional parameter and is used to specify the sort order. It is a comparison function used to determine which value should be ranked first. By default, array elements are rearranged in ascending order .

To this end, the sort() method will call the String conversion function on each element, and then compare the strings to determine the order. Even if the elements of the array are all numerical values, the array elements will first be converted into strings for comparison and sorting.

This results in inaccurate sorting.

let array = [5, 4, 3, 2, 1];
let array2 = array.sort();
console.log(array2)  // [1, 2, 3, 4, 5]

let array = [0, 1, 5, 10, 15];
let array2 = array.sort();
console.log(array2)  //  [0, 1, 10, 15, 5]

For the parameters of the sort() method, it is a comparison function that receives two parameters.

If the first parameter should come before the second parameter, return -1;

If the two parameters are equal, return 0;

If the first parameter should come after the second parameter, return 1.

      function compare(value1, value2) {
        if (value1 < value2) {
          return -1;
        } else if (value1 > value2) {
          return 1;
        } else {
          return 0;
        }
      }

      let array = [1, 5, 0, 15, 10];
      let array2 = array.sort(compare);
      console.log(array2); // [0, 1, 5, 10, 15]

 We use arrow functions to define:

let array = [0, 1, 5, 10, 15];

let array2 = array.sort((a, b) => a - b);  // 正序排序 升序
console.log(array2)  // [0, 1, 5, 10, 15]

let array3 = array.sort((a, b) => b - a);  // 倒序排序 降序
console.log(array3)  // [15, 10, 5, 1, 0]
② reverse()

Reverse the order of elements in an array. This method changes the original array without creating a new array.

      let array = [1, 2, 3, 4, 5];
      let array2 = array.reverse();
      console.log(array); // [5, 4, 3, 2, 1]
      console.log(array2 === array); // true

6. Operation method

① concat()

Concatenate two or more arrays. This method does not modify the existing array, but simply returns a copy of the concatenated array.

This method can also be used for array flattening

arrayObject.concat(arrayX,arrayX,......,arrayX)

The parameter arrayX is required. This parameter can be a specific value or an array object. Can be any number.

      let array = [1, 2, 3];
      let array2 = array.concat(4, [5, 6], [7, 8, 9]);
      console.log(array2); // [1, 2, 3, 4, 5, 6, 7, 8, 9]
      console.log(array); // [1, 2, 3], 可见原数组并未被修改
② slice()

Returns selected elements from an existing array. Returns a new array containing the array elements from start to end (exclusive). The method does not modify the array, but returns a subarray.

arrayObject.slice(start, end) 

Its parameters are as follows:

  • start : required. Specifies where to start the selection. If negative, it specifies the position from the end of the array. That is, -1 refers to the last element, -2 refers to the second to last element, and so on;
  • end : optional. Specifies where the selection ends. This parameter is the array index at the end of the array fragment. If this parameter is not specified, the split array contains all elements from start to the end of the array. If this parameter is negative, it specifies the elements starting from the end of the array.
      let array = ["one", "two", "three", "four", "five"];
      console.log(array.slice(0)); // ["one", "two", "three","four", "five"]
      console.log(array.slice(2, 3)); // ["three"]
③ splice()

One of the most powerful methods on arrays. It adds/removes items to/from the array and returns the removed item. This method mutates the original array. Its usage syntax is as follows:

arrayObject.splice(index, howmany, item1,.....,itemX)

Its parameters are as follows:

  • index: required. An integer specifying the position at which to add/remove an item. Use a negative number to specify the position from the end of the array.
  • howmany: required. The number of items to delete. If set to 0, items will not be deleted.
  • item1, ..., itemX: optional. New items added to the array.

As can be seen from the above parameters, splice mainly has three forms of use:

  • Delete: Two parameters need to be passed, namely the position of the first element to be deleted and the number of elements to be deleted;
  • Insertion: You need to pass at least three parameters, namely the starting position, 0 (the number of elements to be deleted), and the element to be inserted.
  • Replace: Delete an element and insert a new element at the specified position. You also need to pass in at least three parameters, namely the starting position, the number of elements to be deleted, and the elements to be inserted. The number of elements to be inserted is arbitrary and does not necessarily equal the number of elements to be deleted.
      let array1 = ["one", "two", "three", "four", "five"];
      console.log(array1.splice(1, 2)); // 删除:["two", "three"]
      console.log(array1) // ["one", "four", "five"];

      let array2 = ["one", "two", "three", "four", "five"];
      console.log(array2.splice(2, 0, 996)); // 插入:[]
      console.log(array2) // ["one", "two", 996, "three", "four", "five"];

      let array3 = ["one", "two", "three", "four", "five"];
      console.log(array3.splice(2, 1, 996)); // 替换:["three"]
      console.log(array3) //  ["one", "two", 996, "four", "five"];

 

7. Merger method

① reduce()

Commonly used methods for arrays - reduce() method [array summation, multiplication, counting the number of occurrences of each element in the array, array deduplication, converting two-dimensional arrays into one-dimensional, converting multi-dimensional arrays into one-dimensional, objects Sum of attributes]_reduce sum-CSDN Blog

Execute a reducer function (executed in ascending order) on each element in the array, summarizing its results into a single return value.

Execute the callback function in sequence for each element in the array, excluding elements in the array that are deleted or have never been assigned a value.

arr.reduce(callback, [initialValue])

(1) callback(function that executes each value in the array, contains four parameters)

  • previousValue (the value returned from the last callback call, or the provided initialValue)
  • currentValue (the currently processed element in the array)
  • index (the index of the current element in the array)
  • array (the array on which reduce is called)

(2) initialValue(As the first parameter of the first callback.)

let arr = [1, 2, 3, 4]
let sum = arr.reduce((prev, cur, index, arr) => {
    console.log(prev, cur, index);
    return prev + cur;
})
console.log(arr, sum);  

The output is as follows:

1 2 1
3 3 2
6 4 3
[1, 2, 3, 4] 10

If no initialValue is provided, reduce will start executing the callback method from index 1, skipping the first index. If initialValue is provided, starts at index 0. 

let arr = [1, 2, 3, 4]
let sum = arr.reduce((prev, cur, index, arr) => {
    console.log(prev, cur, index);
    return prev + cur;
}, 5)
console.log(arr, sum);  

The output is as follows:

5 1 0
6 2 1
8 3 2
11 4 3
[1, 2, 3, 4] 15

② reduceRight()

This method is almost the same as the above  reduce() usage, except that this method searches the array in reverse order. The methods reduce()are executed in sequence.

      let arr = [1, 2, 3, 4];
      let sum = arr.reduceRight((prev, cur, index, arr) => {
        console.log(prev, cur, index);
        return prev + cur;
      }, 5);
      console.log(arr, sum);

The output is as follows:

5 4 3
9 3 2
12 2 1
14 1 0
[1, 2, 3, 4] 15 

8. Search and location methods

ECMAScript provides two types of methods for searching arrays: searching by strict equality and searching by assertion functions.

① Strictly equal  indexOf(), lastIndexOf(), includes()

ECMAScript passes three strictly equal search methods: indexOf(), lastIndexOf(), and includes() .

These methods all accept two parameters: the element to be found and the optional actual search position

lastIndexOf(): searches forward from the end element of the array , while the other two methods search backward from the beginning element of the array.

indexOf() and lastIndexOf() : return the index value of the element in the array, if not found, return -1

includes(): Returns a Boolean value indicating whether at least one item matching the specified element is found.

When comparing the first argument to each item in the array, a congruent (===) comparison is used, which means that the two items must be strictly equal.

let arr = [1, 2, 3, 4, 5];
console.log(arr.indexOf(2))      // 1
console.log(arr.lastIndexOf(3))  // 2
console.log(arr.includes(4))     // true
② Assertion functions  find(), findIndex()

ECMAScript also allows arrays to be searched according to defined assertion functions. This function is called for each index. The return value of the assertion function determines whether the element at the corresponding index is considered a match.

There are two ways to use assertion functions, namely find() and findIndex() methods.

These two methods will not be executed for empty arrays . And the original value of the array is not changed.

They all have three parameters: element, index, and array object to which the element belongs. where element is the currently searched element in the array, index is the index of the current element, and array is the array currently being searched.

find(): Returns the first matching element . If there is no element that meets the conditions, undefined is returned ;

findIndex(): Returns the index of the first matching element . If there is no element that meets the conditions, it returns -1 .

      let arr = [1, 2, 3, 4, 5];
      arr.find((item) => item > 2); // 结果: 3
      arr.findIndex((item) => item > 2); // 结果: 2

 

9. Iterator methods  keys(), values(), entries()

In ES6, the Array prototype exposes three methods for retrieving array contents: keys(), values(), and entries()

keys(): returns an iterator of array indexes

values(): Returns an iterator of array elements

entries(): returns an iterator of index value pairs

Because these methods return iterators, their contents can be converted directly into array instances through Array.from:

let array = ["one", "two", "three", "four", "five"];
console.log(Array.from(array.keys())); // [0, 1, 2, 3, 4]
console.log(Array.from(array.values())); // ["one", "two", "three", "four", "five"]
console.log(Array.from(array.entries())); // [[0, "one"], [1, "two"], [2, "three"], [3, "four"], [4, "five"]]

 

10. Iteration methods  every(), filter(), forEach(), map(), some()

ECMAScript defines 5 iteration methods for arrays, namely every(), filter(), forEach(), map(), and some()

None of these methods will change the original array . These five methods all receive two parameters: a function to be run with each item as a parameter and an optional scope object as the context in which the function is run (affecting the this value in the function).

The function passed to each method receives three parameters: the current element, the index value of the current element, and the number object to which the current element belongs.

① every()

Iterates through each item in the array and returns true only if all elements meet the conditions, otherwise it returns false.

let arr = [1, 2, 3, 4, 5]
console.log(arr.every(item => item > 0)) // true
② filter()

Used to filter the array, and elements that meet the conditions will be returned.

Its parameter is a callback function. All array elements execute the function in sequence, and the elements whose return result is true will be returned. This method will return a new array and will not change the original array.

let arr = [1, 2, 3, 4, 5]
console.log(arr.filter(item => item > 2)) // [3, 4, 5]

You can use  filter() methods to remove undefined, null, NaN, etc. values ​​from an array

let arr = [1, undefined, 2, null, 3, false, '', 4, 0]
console.log(arr.filter(Boolean)) // [1, 2, 3, 4]
③ forEach

Used to call each element of the array and pass the element to the callback function. This method has no return value 

let arr = [1, 2, 3, 4, 5]
arr.forEach((item, index, arr) => {
  console.log(item, index, arr)
})

This method can also have a second parameter, which is used to bind the this variable inside the callback function (the callback function cannot be an arrow function, because the arrow function does not have this)

      let arr = [1, 2, 3, 4, 5];
      let arr1 = [9, 8, 7, 6, 5];
      arr.forEach(function (item, index, arr) {
        console.log(this[index]); //  9 8 7 6 5
      }, arr1);
④ map()

A new array will be returned, and the elements in the array are the values ​​of the original array elements after calling the function.

This method processes elements sequentially in the original array element order. This method does not detect an empty array , it returns a new array without changing the original array .

      let arr = [1, 2, 3];
      let arrNew = arr.map((item) => {
        return item + 1;
      });
      console.log(arrNew); // [2, 3, 4]

The second parameter is used to bind the this variable inside the parameter function: 

      var arr = ["a", "b", "c"];
      let arrNew = [1, 2].map(function (e) {
        return this[e];
      }, arr);
      console.log(arrNew); // ['b', 'c']

This method can be called in a chain:

      let arr = [1, 2, 3];
      let arrNew = arr.map((item) => item + 1).map((item) => item + 1);
      console.log(arrNew); // [3, 4, 5]
⑤ some()

Iterates through each item in the array and returns true as long as one element meets the condition, otherwise it returns false.

      let arr = [1, 2, 3, 4, 5];
      console.log(arr.some((item) => item > 4)) // true

 

Guess you like

Origin blog.csdn.net/qq_38290251/article/details/134338504