首页 > 语言 > JavaScript > 正文

向JavaScript的数组中添加元素的方法小结

2024-05-06 16:24:51
字体:
来源:转载
供稿:网友

这篇文章主要介绍了向JavaScript的数组中添加元素的方法小结,分别举了一些JS数组操作的例子,基本需要的朋友可以参考下

在数组的开头添加新元素 - unshift()

源代码:

 

  1. <!DOCTYPE html> 
  2. <html> 
  3. <body> 
  4.  
  5. <p id="demo">Click the button to add elements to the array.</p> 
  6.  
  7. <button onclick="myFunction()">Try it</button> 
  8.  
  9. <script> 
  10. function myFunction() 
  11. var fruits = ["Banana""Orange""Apple""Mango"]; 
  12. fruits.unshift("Lemon","Pineapple"); 
  13. var x=document.getElementById("demo"); 
  14. x.innerHTML=fruits; 
  15. </script> 
  16.  
  17. <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> 
  18.  
  19. </body> 
  20. </html>  

测试结果:

  1. Lemon,Pineapple,Banana,Orange,Apple,Mango 


在数组的第2位置添加一个元素 - splice()

源代码:

 

 
  1. <!DOCTYPE html> 
  2. <html> 
  3. <body> 
  4. ​ 
  5. <p id="demo">Click the button to add elements to the array.</p> 
  6. ​ 
  7. <button onclick="myFunction()">Try it</button> 
  8. ​ 
  9. <script> 
  10. function myFunction() 
  11. var fruits = ["Banana""Orange""Apple""Mango"]; 
  12. fruits.splice(2,0,"Lemon","Kiwi"); 
  13. var x=document.getElementById("demo"); 
  14. x.innerHTML=fruits; 
  15. </script> 
  16. ​ 
  17. </body> 
  18. </html>  

测试结果:

 

 
  1. Banana,Orange,Lemon,Kiwi,Apple,Mango 

数组的末尾添加新的元素 - push()

源代码:

 

 
  1. <!DOCTYPE html> 
  2. <html> 
  3. <body> 
  4. ​ 
  5. <p id="demo">Click the button to add a new element to the array.</p> 
  6. ​ 
  7. <button onclick="myFunction()">Try it</button> 
  8. ​ 
  9. <script> 
  10. var fruits = ["Banana""Orange""Apple""Mango"]; 
  11. ​ 
  12. function myFunction() 
  13. fruits.push("Kiwi"
  14. var x=document.getElementById("demo"); 
  15. x.innerHTML=fruits; 
  16. </script> 
  17. ​ 
  18. </body> 
  19. </html>  

测试结果:

 

 
  1. Banana,Orange,Apple,Mango,Kiwi 

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选