本文整理了向JavaScript數組中添加元素的幾種常用方法,分別對應「開頭插入」「指定位置插入」和「末尾追加」三種場景,並附上可運行的示例。
在數組開頭添加新元素 —— unshift()
源代碼:
<!DOCTYPE html> <html> <body> <p id="demo">Click the button to add elements to the array.</p> <button onclick="myFunction()">Try it</button> <script> function myFunction() { var fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.unshift("Lemon","Pineapple"); var x=document.getElementById("demo"); x.innerHTML=fruits; } </script> <p><b>Note:</b> The unshift() method does not work properly in Internet Explorer 8 and earlier, the values will be inserted, but the return value will be <em>undefined</em>.</p> </body> </html> 測試結果:
Lemon,Pineapple,Banana,Orange,Apple,Mango
在數組的指定位置插入元素 —— splice()
源代碼:
<!DOCTYPE html> <html> <body> <p id="demo">Click the button to add elements to the array.</p> <button onclick="myFunction()">Try it</button> <script> function myFunction() { var fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.splice(2,0,"Lemon","Kiwi"); var x=document.getElementById("demo"); x.innerHTML=fruits; } </script> </body> </html> 測試結果:
Banana,Orange,Lemon,Kiwi,Apple,Mango
splice 的第一個參數是起始索引,第二個是刪除個數(這裡為0表示不刪除),後面則是要插入的元素,因此可以精準地把新元素塞進任意位置。
在數組末尾添加新元素 —— push()
源代碼:
<!DOCTYPE html> <html> <body> <p id="demo">Click the button to add a new element to the array.</p> <button onclick="myFunction()">Try it</button> <script> var fruits = ["Banana", "Orange", "Apple", "Mango"]; function myFunction() { fruits.push("Kiwi") var x=document.getElementById("demo"); x.innerHTML=fruits; } </script> </body> </html> 測試結果:
Banana,Orange,Apple,Mango,Kiwi
簡單來說:unshift 往頭部加、push 往尾部加、splice 則能靈活地在任意位置插入,三者搭配幾乎能覆蓋日常所有向數組添加元素的需求。