Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Cách sử dụng toán tử delete trong JavaScript

Toán tử delete trong JavaScript dùng để xóa một thuộc tính khỏi đối tượng.

Ví dụ

Mã dưới đây minh họa xóa thuộc tính price của đối tượng book:

<html>
  <head>
    <title>JavaScript Delete Operator</title>
    <script>
      function book(title, author) {
        this.title = title;
        this.author = author;
      }
    </script>
  </head>
  <body>
    <script>
      var myBook = new book("WordPress Development", "Amit");
      book.prototype.price = null;
      myBook.price = 500;
      document.write("<h2>Details before deleting book price</h2>");
      document.write("Book title is : " + myBook.title + "<br>");
      document.write("Book author is : " + myBook.author + "<br>");
      document.write("Book price is : " + myBook.price);
      delete myBook.price;
      document.write("<br><h2>Details after deleting book price</h2>");
      document.write("Book title is : " + myBook.title + "<br>");
      document.write("Book author is : " + myBook.author + "<br>");
      document.write("Book price is : " + myBook.price + "<br>");
    </script>
  </body>
</html>