JavaScript 中拼接数组是什么意思?举例说明
javascriptweb developmentobject oriented programming
拼接数组是指使用 Array.splice() 方法在数组中添加或删除项。删除的项将作为数组返回。
以下是 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; } .sample,.result { font-size: 20px; font-weight: 500; } </style> </head> <body> <h1>Splicing an array in JavaScript</h1> <div class="sample"></div> <div style="color: green;" class="result"></div> <button class="btn">点击此处</button> <h3> Click on the above button to add items after second element </h3> <script> let fillEle = document.querySelector(".sample"); let resEle = document.querySelector(".result"); let arr = [1, 3, 5, 7, 9, 11]; fillEle.innerHTML = arr; document.querySelector(".Btn").addEventListener("click", () => { arr.splice(2, 0, "A", "B", "C", "D", "E"); resEle.innerHTML = "Spliced array = " + arr; }); </script> </body> </html>
输出
上述代码将产生以下输出 −
点击‘点击此处’按钮 −