JavaScript中如何给数组添加元素

发布时间:2021-08-10 17:22:28 作者:Leah
来源:亿速云 阅读:157

本篇文章给大家分享的是有关JavaScript中如何给数组添加元素,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。

js push()方法添加数组元素

push()方法可以将一个或多个新元素添加到数组的结尾,然后返回新数组的长度,且所有主要浏览器都支持push()方法。

语法:

数组.push(元素1,元素2,元素3.....元素n);/*push()方法里必须有一个参数*/

代码示例:把dog1,dog2两个元素添加到animal数组的末尾

<!DOCTYPE html> 
 <html> 
 <head> 
 <meta charset="UTF-8"> 
 </head> 
 <body> 
 <div class="demo"> 
 <p>数组:cat,elephant,tiger,rabbit;<br>数组长度为:4</p> 
 <button onclick="myFunction()">点我--push()添加元素</button> 
 </div> 
 </body> 
 <script type="text/javascript"> 
 function myFunction(){ 
 var animal = ["cat", "elephant", "tiger","rabbit"]; 
 document.write("<p>数组:"+animal+";<br>数组长度:"+ animal.length+"</p>"); 
 var animal1= animal.push("dog1","dog2"); 
 document.write("<p>新数组:"+animal+";<br>数组长度:"+ animal1+"</p>"); 
 } 
 </script> 
 </html>

说明:

数组.length可以返回数组的长度

js unshift()方法添加数组元素

unshift()方法可以将一个或多个新元素添加到数组的开头,然后返回新数组的长度,且所有主流浏览器都支持unshift方法。

语法:

数组.unshift(元素1,元素2,元素3.....元素n);/* unshift()方法里必须有一个参数*/

代码示例:把dog1,dog2两个元素添加到animal数组的开头

<!DOCTYPE html> 
 <html> 
 <head> 
 <meta charset="UTF-8"> 
 </head> 
 <body> 
 <div class="demo"> 
 <p>数组:cat,elephant,tiger,rabbit;<br>数组长度为:4</p> 
 <button onclick="myFunction()">点我--unshift()添加元素</button> 
 </div> 
 </body> 
 <script type="text/javascript"> 
 function myFunction(){ 
 var animal = ["cat", "elephant", "tiger","rabbit"]; 
 document.write("<p>数组:"+animal+";<br>数组长度:"+ animal.length+"</p>"); 
 var animal1= animal.unshift("dog1","dog2"); 
 document.write("<p>新数组:"+animal+";<br>数组长度:"+ animal1+"</p>"); 
 } 
 </script> 
 </html>

js splice()方法添加数组元素

splice()方法可以将一个或多个新元素添加到数组的指定位置,插入位置的元素自动后移,且所有主要浏览器都支持splice方法。

语法:

数组.splice(index,howmany,item1,.....,itemN);

index:表示从哪里添加或者删除元素;

howmany:表示应该删除多少个元素,赋值为0就表示不删除元素;

item:表示要添加到数组的新元素。

代码示例:把dog1,dog2两个元素添加到animal数组的第二个位置里(第一个元素后)

<!DOCTYPE html> 
 <html> 
 <head> 
 <meta charset="UTF-8"> 
 </head> 
 <body> 
 <div class="demo"> 
 <p>数组:cat,elephant,tiger,rabbit;<br>数组长度为:4</p> 
 <button onclick="myFunction()">点我--splice()添加元素</button> 
 </div> 
 </body> 
 <script type="text/javascript"> 
 function myFunction(){ 
 var animal = ["cat", "elephant", "tiger","rabbit"]; 
 document.write("<p>数组:"+animal+";<br>数组长度:"+ animal.length+"</p>"); 
 var animal1= animal.splice(1,0,"dog1","dog2"); 
 document.write("<p>新数组:"+animal+";<br>数组长度:"+ animal1.length+"</p>"); 
 } 
 </script> 
 </html>

以上就是JavaScript中如何给数组添加元素,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注亿速云行业资讯频道。

推荐阅读:
  1. JavaScript给数组添加元素的方法是什么
  2. 如何添加javascript数组n乘以相同的元素

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

javascript

上一篇:css选择符类型有哪些

下一篇:怎么CSS实现加载功能

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》