如何在 JavaScript 中合并两个数组?
代码如下,可用来在 JavaScript 中合并两个数组 −
示例
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; } .result,.sample { font-size: 18px; font-weight: 500; color: rebeccapurple; } .result { color: red; } </style> </head> <body> <h1>Join two arrays in JavaScript</h1> <div class="sample"></div> <div class="result"></div> <button class="Btn">CLICK HERE</button> <h3>Click the above button to join the above two arrays together.</h3> <script> let BtnEle = document.querySelector(".Btn"); let resEle = document.querySelector(".result"); let sampleEle = document.querySelector(".sample"); let arr = [1, 2, 3, 4]; let arr1 = ["A", "B", "C", "D"]; sampleEle.innerHTML = "arr = " + arr + " " + "arr1 = " + arr1; let mergedArr = arr.concat(arr1); BtnEle.addEventListener("click", () => { resEle.innerHTML = "Merged array = " + mergedArr; }); </script> </body> </html>
输出
上述代码会生成以下输出 −
单击“点此”按钮时 −
广告