将一个元素添加到数组中的位置 2 - splice()

  1. <!DOCTYPE html>
  2. <html>
  3. <body>
  4.  
  5. <h1>JavaScript 数组方法</h1>
  6.  
  7. <h2>splice()</h2>
  8.  
  9. <p>splice() 方法将新元素添加到数组中。</p>
  10.  
  11. <button onclick="myFunction()">试一试</button>
  12.  
  13. <p id="demo1"></p>
  14. <p id="demo2"></p>
  15.  
  16. <script>
  17. var fruits = ["Banana", "Orange", "Apple", "Mango"];
  18. document.getElementById("demo1").innerHTML = "原数组:<br>" + fruits;
  19. function myFunction() {
  20. fruits.splice(2, 0, "Lemon", "Kiwi");
  21. document.getElementById("demo2").innerHTML = "新数组:<br>" + fruits;
  22. }
  23. </script>
  24.  
  25. </body>
  26. </html>