ใช้เมธอด concat()
เหมือนกับการขยาย Array concat() รวม Array ได้หลายตัว และ คืนค่า Array ใหม่ ไม่ Mutate ต้นฉบับ
ตัวอย่างโค้ด
<html>
<head>
<title>JavaScript Array concat Method</title>
</head>
<body>
<script>
var alpha = ["a", "b", "c"];
var numeric = [1, 2, 3];
var alphaNumeric = alpha.concat(numeric);
document.write("alphaNumeric : " + alphaNumeric);
</script>
</body>
</html>
ผลลัพธ์
alphaNumeric : a,b,c,1,2,3
รายละเอียด
alphaและnumericไม่เปลี่ยนแปลงalphaNumericเป็น Array ใหม่ที่มีสมาชิกรวมกัน
<ล>ลำดับสมาชิก: ทั้งหมดของ Array แรก ตามด้วย Array ที่สอง
วิธีอื่นๆ
1. Spread Operator (ES6+) - แนะนำ
const alpha = ['a', 'b', 'c']; const numeric = [1, 2, 3]; const merged = [...alpha, ...numeric]; // ['a', 'b', 'c', 1, 2, 3]
2. push() กับ Spread (Mutate Original)
const alpha = ['a', 'b', 'c']; const numeric = [1, 2, 3]; alpha.push(...numeric); // alpha กลายเป็น ['a', 'b', 'c', 1, 2, 3]
3. สำหรับ Array of Arrays (Flatten)
const arrays = [['a', 'b'], [1, 2], ['x', 'y']]; const merged = [].concat(...arrays); // ['a', 'b', 1, 2, 'x', 'y'] // หรือ ES2019+ const merged2 = arrays.flat(); // ['a', 'b', 1, 2, 'x', 'y']
ตารางเปรียบเทียบ
| วิธี | Mutate? | Syntax | Browser Support |
|---|---|---|---|
concat() | ไม่ | a.concat(b) | All (ES3+) |
Spread | ไม่ | [...a, ...b] | ES6+ (IE: ไม่รองรับ) |
push(...) | ใช่ | a.push(...b) | ES6+ |
flat() | ไม่ | arrays.flat() | ES2019+ |
สรุป
concat() เป็นมาตรฐานเก่าที่ปลอดภัยทุก Browser สำหรับโค้ดสมัยใหม่ ใช้ [...a, ...b] (Spread) อ่านง่ายกว่า ต้องการ Mutate ให้ใช้ push(...b)