Detailed explanation of common methods of JavaScript arrays

Detailed explanation of common methods of JavaScript arrays

Common array methods

  • The push() method adds one or more elements to the end of an array and returns the new length of the array.
  • You can pass the added elements as parameters to the method, and they will be automatically added to the end of the array.
  • This method will return the new length of the array as the return value
var arr = ["Little Monk","Little Monkey","Little Pig","Little Sand","Little Dragon"];
var result = arr.push("Jiang Liu","Xin Yuan","Wooden Dragon","Dao Gui","Yima");
console.log("Return value: "+result);
console.log("New array: "+arr);

insert image description here

pop()

This method can delete the last element of the array and return the deleted element as the return value.

var arr = ["River Flow","Monkey Heart","Wooden Dragon","Knife Sharp","Intentional Horse"];
var result = arr.pop();
console.log("Return value: "+result);
console.log("New array: "+arr);

insert image description here

unshift()

  • Add one or more elements to the beginning of an array and return the new length of the array
  • After inserting elements to the front, the indexes of other elements will be adjusted in sequence
var arr = ["River Flow","Monkey Heart","Wooden Dragon","Knife Sharp","Intentional Horse"];
var result = arr.unshift();
console.log("Return value: "+result);
console.log("New array: "+arr);

insert image description here

shift()

You can delete the first element of an array and use the deleted element as the return value

var arr = ["River Flow","Monkey Heart","Wooden Dragon","Knife Sharp","Intentional Horse"];
var result = arr.shift();
console.log("Return value: "+result);
console.log("New array: "+arr);

insert image description here

slice()

  • Can be used to extract specified elements from an array
  • This method does not change the element array, but encapsulates the intercepted elements into a new array and returns it.

parameter:

  • The first parameter: the index of the start position of the interception, including the start index
  • The second parameter: the index of the end position of the interception, excluding the end index (the intercepted array does not include this value)
  • The second parameter can be omitted, in which case all elements after the start index will be captured.
    • The index can pass a negative value. If a negative value is passed, it is calculated from the back to the front.
    • 1The last one
    • 2The second to last
var arr = ["River Flow","Monkey Heart","Wooden Dragon","Knife Sharp","Intentional Horse"];
var result = arr.slice(1,3);
console.log("The intercepted array: "+result);
console.log("The original array will not change:"+arr);

insert image description here

splice()

  • Can be used to delete a specified element in an array
  • Using this method will affect the original array, delete the specified element from the original array, and use the deleted element as the return value

parameter

  • The first parameter: indicates the index of the starting position, including the starting index
  • The second parameter: indicates the number of deletions, excluding the end index (the array is not included in the interception)
var arr = ["River Flow","Monkey Heart","Wooden Dragon","Knife Sharp","Intentional Horse"];
var result = arr.splice(1,3);
console.log("Deleted element: "+result);
console.log("The original array will change:"+arr);

insert image description here

  • The third parameter and later: you can pass some new elements, which will automatically insert hi before the start position index
var arr = ["River Flow","Monkey Heart","Wooden Dragon","Knife Sharp","Intentional Horse"];
var result = arr.splice(1,2,"孙悟空","猪八戒");
console.log("Deleted element: "+result);
console.log("The original array will change:"+arr);

insert image description here

Array element deduplication

var arr = [1, 1, 5, 6, 4, 5, 2, 3, 7, 9, 4, 4, 4, 1];
for (let i = 0; i < arr.length; i++) {
    for (let j = i + 1; j < arr.length; j++) {
        if (arr[i] === arr[j]) {
            arr.splice(j, 1); //Delete the element j at the current position j--; //After deleting the element j, the following elements will automatically fill in the position, and you need to compare again at the position j}
    }
}
console.log(arr);

concat()

  • This method can concatenate two or more arrays and return the new array.
  • This method will not affect the original array.
var arr1 = ["River Flow","Monkey Heart","Wooden Dragon","Knife Sharp","Intentional Horse"];
var arr2 = ["Tang Monk","Sun Wukong","Zhu Bajie","Sha Monk","White Dragon Horse"];

var result = arr1.concat(arr2,"Mind wandering");
console.log("New array: "+result);

insert image description here

join()

  • This method can convert an array into a string.
  • This method will not affect the original array, but will return the converted string as the result.
  • In join() , you can specify a string as a parameter. This string will become the connector of the elements in the array. If you do not specify a connector, the default connector is ,
var arr = ["River Flow","Monkey Heart","Wooden Dragon","Knife Sharp","Intentional Horse"];

var result = arr.join("-");
console.log("New array: "+result);
console.log("The type of result is: "+typeof(result));

insert image description here

reverse()

  • This method is used to reverse the array (the front elements go to the back, and the back elements go to the front)
  • This method will affect the original array
var arr = ["River Flow","Monkey Heart","Wooden Dragon","Knife Sharp","Intentional Horse"];

arr.reverse();
console.log("arr array after inversion: "+arr);

insert image description here

sort()

This method can sort the elements in an array. This method will affect the original array, and by default it will be sorted according to Unicode encoding.

var arr = ["a","d","g","f","k",'v',"d","x"];
arr.sort();
console.log("sorted arr array: "+arr);

insert image description here

Even for an array of pure numbers, when sort() is used, it will be sorted according to Unicode encoding, so sorting numbers may give incorrect answers.

var arr = [2,14,12,3,5,53,7,31,13];
arr.sort();
console.log("sorted arr array: "+arr);

insert image description here

You can specify your own sorting rules

Add a callback function to sort() to specify the sorting rules

Two parameters (a, b) need to be defined in the callback function

The browser will use the elements in the array as arguments to call the callback function

The browser will determine the order of elements based on the return value of the callback function

  • If a value greater than 0 is returned, the elements are swapped.
  • If a value less than 0 is returned, the element position remains unchanged.
  • If a 0 is returned, the two elements are considered equal and their positions are not swapped.
  • If ascending order is required, return a - b
  • If descending sorting is required, return b - a
var arr = [2, 14, 12, 3, 5, 53, 7, 31, 13];
arr.sort(function (a, b) {
   return a - b; // ascending order //return b - a; descending order });
console.log("sorted arr array: " + arr);

insert image description here

Summarize

This article ends here. I hope it can be helpful to you. I also hope you can pay more attention to more content on 123WORDPRESS.COM!

You may also be interested in:
  • Complete list of javascript array methods
  • JS one-dimensional array converted to three-dimensional array method
  • Detailed Example of JavaScript Array Methods
  • Detailed explanation of JS array methods
  • js array fill() filling method
  • Let's learn about javascript array methods

<<:  CSS perfectly solves the problem of front-end image deformation

>>:  MySQL full-text search usage examples

Recommend

Summary of js execution context and scope

Table of contents Preface text 1. Concepts relate...

Example of how to set div background transparent

There are two common ways to make div background ...

MySQL Series 10 MySQL Transaction Isolation to Implement Concurrency Control

Table of contents 1. Concurrent access control 2....

Docker custom network container interconnection

Table of contents Preface –link Custom Network As...

MySQL 5.7.23 installation and configuration graphic tutorial

This article records the detailed installation pr...

Method of dynamically loading geojson based on Vue+Openlayer

Load one or more features <template> <di...

How to install docker on Linux system and log in to docker container through ssh

Note: I use Centos to install docker Step 1: Inst...

The DOCTYPE mode selection mechanism of well-known browsers

Document Scope This article covers mode switching...

Basic use of javascript array includes and reduce

Table of contents Preface Array.prototype.include...

Example of how to use CSS3 to layout elements around a center point

This article introduces an example of how CSS3 ca...

Detailed explanation of how Angular handles unexpected exception errors

Written in front No matter how well the code is w...