Devdit
 

JavaScript ต่อ array เข้าด้วยกัน ด้วยคำสั่ง concat

1.4K

สอนเขียน JavaScript ต่อ array เข้าด้วยกัน ด้วยคำสั่ง concat ตัวอย่างแนะนำการใช้คำสั่ง concat สำหรับต่อ array 2 ตัวเข้าด้วยกัน บทความนี้แนะนำการต่อ array พร้อมกับแสดงผลลัพธ์จากการต่อ array ด้วยคำสั่ง console.log สามารถเขียนโปรแกรมได้ดังนี้

 

ตัวอย่าง JavaScript ต่อ array เข้าด้วยกัน ด้วยคำสั่ง concat

<script>
    const color1 = ["red", "green"];
    const color2 = ["blue", "black", "white"];
    const colors = color1.concat(color2);
    console.log( colors );
</script>

ผลลัพธ์

(5) ['red', 'green', 'blue', 'black', 'white']

คำอธิบาย

JavaScript ต่อ array ตัวอย่างมีตัวแปร array 2 ตัว คือ color1 และ color2 กรณีต้องการต่อ array 2 ตัวเข้าด้วยกัน ใช้คำสั่ง color1.concat(color2) แนะนำให้สร้างตัวแปรขึ้นมารับค่าการต่อ array ที่เกิดขึ้นใหม่ จากตัวอย่างคือ ตัวแปรชื่อ colors

เขียน 2 ปีที่แล้ว
ชอบ
ลิ้งก์
แชร์
Devdit มีช่อง YouTube แล้ว
เราสร้างวิดีโอเกี่ยวกับเทคโนโลยี ทำตามง่ายๆ