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

วิธีสร้าง Array เต็มศูนย์ (Zero-filled Array) ใน JavaScript

ใช้ Typed Array: Uint8Array

วิธีที่มีประสิทธิภาพและชัดเจนที่สุดคือใช้ Uint8Array (Unsigned 8-bit Integer Array) ซึ่งสร้าง Array ขนาดกำหนดเต็มไปด้วย 0 อัตโนมัติ

ตัวอย่างโค้ด

<html>
<body>
  <script>
    var arr1 = ["marketing", "technical", "finance", "sales"];
    var arr2 = new Uint8Array(4); // สร้าง Array 4 Element เต็ม 0
    document.write(arr1);
    document.write("<br>Zero filled array: " + arr2);
  </script>
</body>
</html>

ผลลัพธ์

marketing,technical,finance,sales
Zero filled array: 0,0,0,0

Typed Array Types อื่นๆ

Type Size Range ใช้สำหรับ
Int8Array1 Byte-128 ถึง 127Signed Integer
Uint8Array1 Byte0 ถึง 255Bytes, Binary Data, Zero-filled
Uint8ClampedArray1 Byte0 ถึง 255 (Clamped)Canvas/Image Data
Int16Array2 Bytes-32768 ถึง 32767Short Integer
Uint16Array2 Bytes0 ถึง 65535Unsigned Short
Int32Array4 Bytes-2^31 ถึง 2^31-1Standard Integer
Uint32Array4 Bytes0 ถึง 2^32-1Unsigned Integer
Float32Array4 BytesIEEE 754 FloatFloating Point
Float64Array8 BytesIEEE 754 DoubleHigh Precision Float

วิธีอื่นๆ สำหรับ Regular Array

1. Array.from() (ES6+)

const arr = Array.from({length: 5}, () => 0); // [0, 0, 0, 0, 0]

2. Array Constructor + fill() (ES6+)

const arr = new Array(5).fill(0); // [0, 0, 0, 0, 0]

3. Spread + Array Constructor (ES6+)

const arr = [...new Array(5)].map(() => 0); // [0, 0, 0, 0, 0]

4. Loop แบบคลาสสิก

const arr = [];
for (let i = 0; i < 5; i++) arr.push(0);

ตารางเปรียบเทียบ

วิธี Type Performance Use Case
new Uint8Array(n)Typed Arrayเร็วที่สุด Memory EfficientBinary Data, Buffer, High Perf
Array(n).fill(0)Regular ArrayดีGeneral Purpose
Array.from({length:n}, ()=>0)Regular Arrayดีต้องการ Map Function

ข้อควรระวัง

  • Typed Array (Uint8Array) ไม่ใช่ Array ปกติ ไม่มีเมธอดครบ เช่น push, pop, splice แต่มี set, subarray
  • แปลงเป็น Regular Array: [...uint8Array] หรือ Array.from(uint8Array)
  • new Array(n) สร้าง Array ที่มี length = n แต่เป็น Empty Slots (ไม่ใช่ undefined) ต้องใช้ fill() หรือ Array.from

สรุป

สร้าง Zero-filled Array: new Uint8Array(n) เร็วที่สุดสำหรับ Binary/Data Processing สำหรับ Regular Array ใช้ Array(n).fill(0) หรือ Array.from({length:n}, ()=>0)