国产探花免费观看_亚洲丰满少妇自慰呻吟_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 

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

圖片精選

主站蜘蛛池模板: 双城市| 寿光市| 洛浦县| 通渭县| 正安县| 霍州市| 清丰县| 女性| 麻栗坡县| 平顶山市| 平遥县| 兴和县| 亳州市| 三台县| 永福县| 资溪县| 克拉玛依市| 明溪县| 娱乐| 北安市| 青冈县| 珠海市| 新化县| 阿鲁科尔沁旗| 隆回县| 通山县| 库尔勒市| 当阳市| 开封市| 峨眉山市| 翁牛特旗| 和静县| 敖汉旗| 定结县| 海原县| 岢岚县| 射阳县| 隆安县| 贵德县| 呼伦贝尔市| 江都市|