首页 > web前端 > js教程 > 正文

JS数组添加元素方法总结

韦小宝
发布: 2018-01-26 11:05:22
原创
4205人浏览过

本篇文章介绍了如何向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数组添加元素方法总结的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号