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

Phương thức JavaScript Array.splice ()

Phương thức splice () của JavaScript được sử dụng để thêm hoặc bớt mục. Nó trả về mục đã loại bỏ.

Cú pháp như sau -

array.splice(index, num, item1, ....., itemX)

Ở đây, chỉ mục là số nguyên xác định vị trí cần thêm hoặc xóa mục, num là số mục cần xóa, item1… itemX là các mục sẽ được thêm vào mảng.

Bây giờ chúng ta hãy triển khai phương thức splice () trong JavaScript -

Ví dụ

<!DOCTYPE html>
<html>
<body>
<h2>Products</h2>
<p>Click to display the updated product list...</p>
<button onclick="display()">Result</button>
<p id="test"></p>
<script>
   var products = ["Electronics", "Books", "Accessories"];
   document.getElementById("test").innerHTML = products;
   function display() {
      products.splice(1, 2, "Pet Supplies", "Footwear");
      document.getElementById("test").innerHTML = products;
   }
</script>
</body>
</html>

Đầu ra

Phương thức JavaScript Array.splice ()

Nhấp vào nút "Kết quả" ở trên -

Phương thức JavaScript Array.splice ()

Ví dụ

<!DOCTYPE html>
<html>
<body>
<h2>Products</h2>
<p>Click to display the updated product list...</p>
<button onclick="display()">Result</button>
<p id="test"></p>
<script>
   var products = ["Electronics", "Books", "Accessories"];
   document.getElementById("test").innerHTML = products;
   function display() {
      products.splice(3, 1, "Pet Supplies", "Footwear", "Home Appliances");
      document.getElementById("test").innerHTML = products;
   }
</script>
</body>
</html>

Đầu ra

Phương thức JavaScript Array.splice ()

Nhấp vào nút "Kết quả" -

Phương thức JavaScript Array.splice ()