Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

พรอเพอร์ตี้ของ Array Object ใน JavaScript

Array object เก็บค่าหลายค่าในตัวแปรเดียว เป็น fixed-size sequential collection ของ elements ชนิดเดียวกัน

Properties ของ Array Object

#Propertyคำอธิบาย
1constructorReference ไปยัง array function ที่สร้าง object
2indexZero-based index ของ match ใน string (สำหรับ regex match arrays)
3inputString ต้นฉบับ (สำหรับ arrays จาก regex match)
4lengthจำนวน elements ในอาร์เรย์ (unsigned 32-bit integer)
5prototypeเพิ่ม properties/methods ให้ object ทุกตัวจาก constructor นั้น

ตัวอย่าง: ใช้ prototype เพิ่ม property

<html>
  <head>
    <title>JavaScript Array Object</title>
    <script>
      function book(title, author){
        this.title = title;
        this.author = author;
      }
    </script>
  </head>
  <body>
    <script>
      var myBook = new book("Java", "John");
      book.prototype.price = null;
      myBook.price = 300;
      document.write("Book title: " + myBook.title + "<br>");
      document.write("Book author: " + myBook.author + "<br>");
      document.write("Book price: " + myBook.price + "<br>");
    </script>
  </body>
</html>

ผลลัพธ์

Book title is: Java
Book author is: John
Book price is: 300

length Property – สำคัญที่สุด

var arr = [1, 2, 3];
arr.length;        // 3
arr.length = 5;    // ขยาย array (เพิ่ม empty slots)
arr.length = 1;    // ตัด array เหลือ 1 element
arr[10] = 100;     // length กลายเป็น 11 (auto-expand)

หมายเหตุ: ตัวอย่างในบทความใช้ prototype กับ constructor function (book) ไม่ใช่ array โดยตรง – เป็นตัวอย่าง prototype pattern ทั่วไป