Several ways to empty arrays in JS

1. Change the array to [] to clear the array. If there are multiple references, the array exists in memory and is referenced by other variables.

let user = [{ name: 'zs' }, { name: 'lisi' }];
user = [];
console.log(user);

2. Assign the length of the array to 0

  When the value of the length attribute is less than the length of the array itself, the following elements in the array will be truncated; if the value of the length attribute is 0, the entire array can be cleared.

let user = [{ name: 'zs' }, { name: 'lisi' }];
user.length = 0;
console.log(user);

3. Use splice to clear the array

The splice method is used for arrays or pseudo-arrays . Depending on the number and form of parameters, specified elements can be deleted, inserted, or replaced in the array, and the original array will change.

When there is only one parameter, splice(i) means to delete all the values ​​starting from the i subscript (including the i subscript). When i is a negative value, it starts counting from the back, -1 represents the last item of the array, and so on.

When i is an integer, output the last six elements of the array

let arr = [1, 2, 3, 4, 5, 6, 7];
// 删除数组的后面六个元素
console.log(arr.splice(1));  // [2,3,4,5,6,7]
console.log(arr); // [1]

When i is negative, delete the last three elements of the array

let arr = [1, 2, 3, 4, 5, 6, 7];
// 删除数组的后面三个元素
console.log(arr.splice(-3));  // [5,6,7]
console.log(arr); // [1,2,3,4]

When there are only two parameters, splice(i, num) means to delete the num numbers starting from subscript i (including subscript i), and change the original array.

let arr = [1, 2, 3, 4, 5, 6, 7];
// 删除数组的后面六个元素
console.log(arr.splice(1, 2)); // [2,3]
console.log(arr); // [1,4,5,6,7]

When there are three parameters, splice(i,num,value1,value2,value3...) means to delete the num numbers starting from subscript i (including subscript i) ,

Then insert the value of the following parameters value1, value2, value3 at the position of the subscript i. Each parameter represents each item of the array

let arr = [1, 2, 3, 4, 5, 6, 7]
// 删除数组的后面2个参数,并替换为'green','red'
console.log(arr.splice(5, 2, 'green', 'red')); // [6,7]
console.log(arr); // [1,2,3,4,5,'green','red']

We can delete all the values ​​​​of the array according to splice(0, arr.length) to achieve the purpose of emptying the array

let arr = [1, 2, 3, 4, 5, 6, 7];
console.log(arr.splice(0,arr.length)); // [1, 2, 3, 4, 5, 6, 7]
console.log(arr); // []

4. Delete all the arrays through the array method pop()

let user = [{ name: 'zs' }, { name: 'lisi' }];
while (user.pop()) {}
console.log(user); // []

Guess you like

Origin blog.csdn.net/qq_63299825/article/details/131037627