最新文章专题视频专题问答1问答10问答100问答1000问答2000关键字专题1关键字专题50关键字专题500关键字专题1500TAG最新视频文章推荐1 推荐3 推荐5 推荐7 推荐9 推荐11 推荐13 推荐15 推荐17 推荐19 推荐21 推荐23 推荐25 推荐27 推荐29 推荐31 推荐33 推荐35 推荐37视频文章20视频文章30视频文章40视频文章50视频文章60 视频文章70视频文章80视频文章90视频文章100视频文章120视频文章140 视频2关键字专题关键字专题tag2tag3文章专题文章专题2文章索引1文章索引2文章索引3文章索引4文章索引5123456789101112131415文章专题3
当前位置: 首页 - 科技 - 知识百科 - 正文

JS数组添加元素方法总结

来源:动视网 责编:小采 时间:2020-11-27 20:04:45
文档

JS数组添加元素方法总结

JS数组添加元素方法总结:本篇文章介绍了如何向JS数组中添加新的元素,分别使用不同的几种方法去给JS数组添加元素,数组在JS中是很常用的数据类型之一,而对数组进行操作这是我们必会的基础之一。下面我们来看一下有哪些方法可以对JS数组进行元素的添加!在数组的开头添加新元素 -
推荐度:
导读JS数组添加元素方法总结:本篇文章介绍了如何向JS数组中添加新的元素,分别使用不同的几种方法去给JS数组添加元素,数组在JS中是很常用的数据类型之一,而对数组进行操作这是我们必会的基础之一。下面我们来看一下有哪些方法可以对JS数组进行元素的添加!在数组的开头添加新元素 -


本篇文章介绍了如何向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数组添加元素方法总结

JS数组添加元素方法总结:本篇文章介绍了如何向JS数组中添加新的元素,分别使用不同的几种方法去给JS数组添加元素,数组在JS中是很常用的数据类型之一,而对数组进行操作这是我们必会的基础之一。下面我们来看一下有哪些方法可以对JS数组进行元素的添加!在数组的开头添加新元素 -
推荐度:
标签: 添加 方法 元素
  • 热门焦点

最新推荐

猜你喜欢

热门推荐

专题
Top