How to Empty an Array in JavaScript

Asked 2 years ago, Updated 2 years ago, 41 views

Will JavaScript Empty Array? Is it possible with .remove()?

array javascript

2022-09-22 14:59

1 Answers

There are many ways, but to give you two ways, Suppose you have array A.

A = []; There's a way to do that. This means that you assign a new empty array to A. If it is not necessary to refer to the existing array A, It's the best way.

var arr1 = ['a','b','c','d','e','f'];
Assign a reference of var arr2 = arr1; // arr1 to arr2 
arr1 = [];
console.log(arr2); // Output ['a','b','c','d','e','f']

You can write it like this.

The second method is A.splice(0,A.length); That's how you do it. A.length represents the length of A, and splice is the method of erasing the element by the size of the first parameter to the second parameter.


2022-09-22 14:59

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.