要将新值添加到现有数组,请使用JavaScriptsplice()
方法。
您可以尝试运行以下代码以添加新值-
<html> <head> <title>JavaScript Array splice Method</title> </head> <body> <script> var arr = ["orange", "mango", "banana", "sugar", "tea"]; document.write("原始数组:"+arr) var newArr = arr.splice(2, 0, "water"); document.write("<br>After adding new element: " + arr ); </script> </body> </html>
输出结果
原始数组:orange,mango,banana,sugar,tea After adding new element: orange,mango,water,banana,sugar,tea