ใช้ 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 | ใช้สำหรับ |
|---|---|---|---|
Int8Array | 1 Byte | -128 ถึง 127 | Signed Integer |
Uint8Array | 1 Byte | 0 ถึง 255 | Bytes, Binary Data, Zero-filled |
Uint8ClampedArray | 1 Byte | 0 ถึง 255 (Clamped) | Canvas/Image Data |
Int16Array | 2 Bytes | -32768 ถึง 32767 | Short Integer |
Uint16Array | 2 Bytes | 0 ถึง 65535 | Unsigned Short |
Int32Array | 4 Bytes | -2^31 ถึง 2^31-1 | Standard Integer |
Uint32Array | 4 Bytes | 0 ถึง 2^32-1 | Unsigned Integer |
Float32Array | 4 Bytes | IEEE 754 Float | Floating Point |
Float64Array | 8 Bytes | IEEE 754 Double | High 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 Efficient | Binary 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)