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

วิธีรวม (Merge) สอง Array ใน JavaScript

ใช้เมธอด 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)