乐闻世界logo
搜索文章和话题

How do I empty an array in JavaScript?

1个答案

1

Clearing an array in JavaScript can be done in multiple ways, each suitable for different scenarios. I will introduce several common methods with examples.

Method 1: Set Array Length to 0

This is the simplest and fastest approach. By directly setting the array's length property to 0, you can immediately clear the array.

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

Method 2: Using Array.splice()

The splice() method modifies the array's content, allowing you to delete, replace, or add elements. To clear the array, remove all elements starting from index 0.

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

Method 3: Reassign to a New Empty Array

Directly reassign the array to a new empty array, which discards the original reference and clears the array content.

javascript
let arr = [1, 2, 3, 4, 5]; arr = []; console.log(arr); // Output []

Method 4: Using Array.pop()

Although less efficient, you can use a loop combined with pop() to clear the array. The pop() method removes the last element and returns it.

javascript
let arr = [1, 2, 3, 4, 5]; while(arr.length > 0) { arr.pop(); } console.log(arr); // Output []

Choosing the Right Method

  • For quick clearing without reference concerns, setting length = 0 is optimal.
  • If the array is referenced by multiple variables and you want all references to point to an empty array, use splice() or a loop with pop().
  • If you simply want to discard the old array and create a new one, directly reassign to [].

These methods cover various scenarios, and you can select the most appropriate method based on your specific needs and context.

2024年6月29日 12:07 回复

你的答案