本篇文章介绍了如何向js数组中添加新的元素,分别使用不同的几种方法去给js数组添加元素,数组在js中是很常用的数据类型之一,而对数组进行操作这是我们必会的基础之一。
下面我们来看一下有哪些方法可以对js数组进行元素的添加!
在数组的开头添加新元素 - 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
这些方法每个都有自己的好处,对于js中数组操作不太熟悉的同学更要好好的来练习一下哦!
推荐阅读:
javascript数组中关于push方法的注意事项
push() 方法可向数组的末尾添加一个或多个元素,并返回新的长度。
javascript数组去重/查找/插入/删除的方法
本篇文章是对数组的多种操作。
javascript数组删除特定元素方法介绍
js数组中删除指定元素是我们每个人都遇到的问题
以上就是js数组添加元素方法总结的详细内容。