Computer >> Máy Tính >  >> Lập trình >> Javascript

Làm cách nào để xóa các phần tử bằng phương thức splice () trong JavaScript?


Sau đây là mã để xóa các phần tử bằng phương thức splice () trong JavaScript -

Ví dụ

<!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;
   }
   .sample,.result {
      font-size: 20px;
      font-weight: 500;
   }
</style>
</head>
<body>
<h1>Remove elements using splice()</h1>
<div class="sample"></div>
<div style="color: green;" class="result"></div>
<button class="Btn">CLICK HERE</button>
<h3>Click on the above button to remove elements between 1st and 5th element</h3>
<script>
   let fillEle = document.querySelector(".sample");
   let resEle = document.querySelector(".result");
   let arr = [1, 3, 5, 7, 9, 11];
   fillEle.innerHTML = arr;
   document.querySelector(".Btn").addEventListener("click", () => {
      arr.splice(1, 4);
      resEle.innerHTML = "Spliced array = " + arr;
   });
</script>
</body>
</html>

Đầu ra

Đoạn mã trên sẽ tạo ra kết quả sau -

Làm cách nào để xóa các phần tử bằng phương thức splice () trong JavaScript?

Khi nhấp vào nút 'BẤM VÀO ĐÂY' -

Làm cách nào để xóa các phần tử bằng phương thức splice () trong JavaScript?