在JavaScript中使用unshift()方法可以将点添加到数组开头。使用splice()方法可以将点添加到数组指定位置。使用push()方法可以将点添加到数组末尾。
JavaScript中将点添加到数组中的方法:
1、在数组的开头添加新元素 - unshift()
<!DOCTYPE html> <html> <body> <p id="demo">Click the button to add elements to the array.</p> <button onclick="myFunction()">Try it</button> <script> function myFunction() { var fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.unshift(".","Pineapple"); var x=document.getElementById("demo"); x.innerHTML=fruits; } </script> </body> </html>
测试结果:
.,Pineapple,Banana,Orange,Apple,Mango
2、在数组的指定位置添加一个元素 - splice()
<!DOCTYPE html> <html> <body> <p id="demo">Click the button to add elements to the array.</p> <button onclick="myFunction()">Try it</button> <script> function myFunction() { var fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.splice(2,0,"."); var x=document.getElementById("demo"); x.innerHTML=fruits; } </script> </body> </html>
测试结果:
Banana,Orange,.,Apple,Mango
3、数组的末尾添加新的元素 - push()
<!DOCTYPE html> <html> <body> <p id="demo">Click the button to add a new element to the array</p> <button onclick="myFunction()">Try it</button> <script language="JavaScript"> var fruits = ["Banana", "Orange", "Apple", "Mango"]; function myFunction() { fruits.push(".") var x=document.getElementById("demo"); x.innerHTML=fruits; } </script> </body> </html>
测试结果:
Banana,Orange,Apple,Mango,.
网友评论文明上网理性发言 已有0人参与
发表评论: