iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 10
0
Modern Web

從Stack Overflow學前端系列 第 10

從StackOverflow上學CODING(10)如何清空陣列

  • 分享至 

  • xImage
  •  

How do I empty an array in JavaScript?

Is there a way to empty an array and if so possibly with .remove()?
For instance,
有沒有甚麼方法可以清空陣列?

A = [1,2,3,4];
A = [];

This code will set the variable A to a new empty array. This is perfect if you don't have references to the original array A anywhere else because this actually creates a brand new (empty) array. You should be careful with this method because if you have referenced this array from another variable or property, the original array will remain unchanged. Only use this if you only reference the array by its original variable A.
此方法會設變數A為一個空陣列,在變數A是沒有任何有相關聯的變數的情況下是最完美的,這個方式其實會創造一個新的空陣列,但也有很多地方要注意:這個方式在變數是有相關聯或者有多個定義的情況下會無法生效,請在確認變數A是沒有其他關連與定義的情況下使用

This code sample shows the issue you can encounter when using this method:
下方舉例會失效的情況:

var arr1 = ['a','b','c','d','e','f'];
var arr2 = arr1;  // Reference arr1 by another variable 
arr1 = [];
console.log(arr2); // Output ['a','b','c','d','e','f']
A.length = 0

This will clear the existing array by setting its length to 0. Some have argued that this may not work in all implementations of JavaScript, but it turns out that this is not the case. It also works when using "strict mode" in ECMAScript 5 because the length property of an array is a read/write property.
這個方式會把陣列長度設為0,有些人表示這個方式不是在所有場景都適用,但是我發現他仍然在大部分的地方都很適用,即使在嚴僅模式都可以用

A.splice(0,A.length)

Using .splice() will work perfectly, but since the .splice() function will return an array with all the removed items, it will actually return a copy of the original array. Benchmarks suggest that this has no effect on performance whatsoever.
使用.splice()會完美的達成你的目標,但是.splice()會返回一個陣列與所有你刪除的物件,但不影響效能

while(A.length > 0) {
    A.pop();
}

This solution is not very succinct, and it is also the slowest solution, contrary to earlier benchmarks referenced in the original answer.
此方法並不是非常的簡潔,也是最慢的解決方法


Performance 效能

Of all the methods of clearing an existing array, methods 2 and 3 are very similar in performance and are a lot faster than method 4. See this benchmark.
在以上的解決方式中2、3的效能表現相當接近,且也都比4快很多


上一篇
從StackOverflow上學CODING(9)某物件是否存在的判斷式該怎麼寫
下一篇
從StackOverflow上學CODING(11)網頁localStrorage的存取
系列文
從Stack Overflow學前端30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言