Several ways to append data to an array in js

In JavaScript, there are several ways to append data to an array, including:

  1. push() method: Add one or more elements to the end of the array and return the length of the new array.
javascriptCopy code

var arr = [1, 2, 3]; arr.push(4); console.log(arr); // [1, 2, 3, 4]

  1. unshift() method: Add one or more elements to the beginning of the array and return the length of the new array.
javascriptCopy code

var arr = [2, 3, 4]; arr.unshift(1); console.log(arr); // [1, 2, 3, 4]

  1. splice() method: elements can be added or removed anywhere in the array.
javascriptCopy code

var arr = [1, 2, 4]; arr.splice(2, 0, 3); console.log(arr); // [1, 2, 3, 4]

Among them, the first parameter of the splice() method indicates the starting position of the element to be added or deleted, the second parameter indicates the number of elements to be deleted, and the third parameter and subsequent parameters indicate the element to be added to the array .

  1. concat() method: Combine two or more arrays into a new array.
javascriptCopy code

var arr1 = [1, 2]; var arr2 = [3, 4]; var arr3 = arr1.concat(arr2); console.log(arr3); // [1, 2, 3, 4]

Guess you like

Origin blog.csdn.net/m0_62843289/article/details/130713093