×

JavaScript中使用unshift()方法可以将点添加到数组开头

作者:andy0012020.03.02来源:Web前端之家浏览:5571评论:0
关键词:jsunshift()

在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,.

您的支持是我们创作的动力!
温馨提示:本文作者系 ,经Web前端之家编辑修改或补充,转载请注明出处和本文链接:
https://www.jiangweishan.com/article/js83098903859e08rwe08r.html

网友评论文明上网理性发言 已有0人参与

发表评论: