国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 語言 > 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. <p id="demo">Click the button to add elements to the array.</p> 
  5. <button onclick="myFunction()">Try it</button> 
  6. <script> 
  7. function myFunction() 
  8. var fruits = ["Banana""Orange""Apple""Mango"]; 
  9. fruits.splice(2,0,"Lemon","Kiwi"); 
  10. var x=document.getElementById("demo"); 
  11. x.innerHTML=fruits; 
  12. </script> 
  13. </body> 
  14. </html>  

測試結果:

 

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

數組的末尾添加新的元素 - push()

源代碼:

 

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

測試結果:

 

 
  1. Banana,Orange,Apple,Mango,Kiwi 

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表

圖片精選

主站蜘蛛池模板: 思茅市| 柳林县| 集安市| 潼关县| 新闻| 安乡县| 全椒县| 松潘县| 喀喇沁旗| 漳平市| 景谷| 江城| 青铜峡市| 大竹县| 德阳市| 修水县| 娄烦县| 江华| 乃东县| 乌苏市| 安顺市| 冀州市| 南漳县| 贡嘎县| 靖远县| 会昌县| 泸州市| 宜城市| 大埔区| 武穴市| 洪洞县| 大渡口区| 阜城县| 霍邱县| 隆林| 屯门区| 仪陇县| 宣恩县| 临邑县| 伊川县| 邢台市|