js向数组添加元素

本文转载自http://www.jb51.net/article/73867.htm
仅为学习之用,保存防丢失

在数组的开头添加新元素 - 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("Lemon","Pineapple");
var x=document.getElementById("demo");
x.innerHTML=fruits;
}
</script>

<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>

</body>
</html> 
  • 结果
    Lemon,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,"Lemon","Kiwi");
var x=document.getElementById("demo");
x.innerHTML=fruits;
}
</script></body>
</html> 
  • 结果
    Banana,Orange,Lemon,Kiwi,Apple,Mango

数组的末尾添加新的元素 - 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>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
​
function myFunction()
{
fruits.push("Kiwi")
var x=document.getElementById("demo");
x.innerHTML=fruits;
}
</script></body>
</html> 
  • 结果
    Banana,Orange,Apple,Mango,Kiwi
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值