ในการล้างอาร์เรย์ใน JavaScript มีสี่วิธี -
- การตั้งค่าอาร์เรย์ใหม่ − ในที่นี้ เราตั้งค่าตัวแปรอาร์เรย์เป็นอาร์เรย์ว่างใหม่
- การใช้คุณสมบัติความยาว − ในที่นี้ เราตั้งค่าคุณสมบัติความยาวของอาร์เรย์เป็น 0
- ใช้ป๊อป − ในที่นี้ เราเปิดองค์ประกอบอาร์เรย์อย่างต่อเนื่องจนมีความยาวถึง 0
- การใช้ประกบ − ในนี้ เราใส่ดัชนีเริ่มต้นเป็น 0 และจำนวนองค์ประกอบที่จะลบออกเป็น array.length-1
ต่อไปนี้เป็นรหัสเพื่อแสดงหมายเลข วิธีการล้างอาร์เรย์ใน JavaScript -
ตัวอย่าง
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
body {
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}
.result,
.sample {
font-size: 20px;
font-weight: 500;
color: blueviolet;
}
.sample {
color: red;
}
</style>
</head>
<body>
<h1>No of ways to empty an array in JavaScript</h1>
<div class="sample">
a=[1,2,3,4],b=['a','b','c'],c=['A','B','C','D'],d=[11,22,33,44]
</div>
<div class="result"></div>
<button class="Btn">CLICK HERE</button>
<h3>Click on the above button to empty the above arrays</h3>
<script>
let resEle = document.querySelector(".result");
let a, b, c, d;
(a = [1, 2, 3, 4]),
(b = ["a", "b", "c"]),
(c = ["A", "B", "C", "D"]),
(d = [11, 22, 33, 44]);
document.querySelector(".Btn").addEventListener("click", () => {
let emptyArr = [];
a = emptyArr;
resEle.innerHTML = " a = " + a + "<br>";
b.length = 0;
resEle.innerHTML += " b = " + b + "<br>";
while (c.length > 0) {
c.pop();
}
resEle.innerHTML += "c = " + c + "<br>";
d.splice(0, d.length);
resEle.innerHTML += "d = " + d + "<br>";
});
</script>
</body>
</html> ผลลัพธ์

เมื่อคลิกปุ่ม 'คลิกที่นี่' -
