如何在 JavaScript 中清空陣列?


在 javascript 中清空陣列有幾種方法。

假設有一個數組

var array1 = [1,2,3,4,5,6,7];

方法 1

var array1 = [];

以上程式碼將數字陣列設定為一個新的空陣列。當沒有對原始陣列“array1”的任何引用時,建議使用此方法。使用此方法清空陣列時,您應該小心,因為如果您透過其他變數引用了此陣列,則原始引用陣列將保持不變。

示例

<html>
<body>
<script>
   var array1 = [1,2,3,4,5,6,7];  // Created array
   var anotherArray = array1;     // Referenced array1 by another variable
   array1 = [];                   // Empty the array
   document.write(anotherArray);  // Output [1,2,3,4,5,6,7]
</script>
</body>
</html>

方法 2

var array1.length = 0;

以上的程式碼行將原始陣列的長度變為 0,從而清空陣列。

示例

<html>
<body>
<script>
   var array1 = [1,2,3,4,5,6,7]; // Created array
   var anotherArray = array1; // Referenced array1 by another variable
   array1.length = 0; // Empty the array by setting length to 0
   console.log(anotherArray); // Output []
</script>
</body>
</html>

方法 3

array1.splice(0, array1.length);

以上程式碼行也完美有效。這種方式的程式碼將更新原始陣列的所有引用。

示例

<html>
<body>
<script>
   var array1 = [1,2,3,4,5,6,7]; // Created array
   var anotherArray = array1; // Referenced array1 by another variable
   array1.splice(0, array1.length); // Empty the array by setting length to 0
   console.log(anotherArray); // Output []
</script>
</body>
</html>

更新於: 2019 年 7 月 30 日

793 次瀏覽

開啟你的職業

完成課程即可獲得認證

開始
廣告
© . All rights reserved.