JavaScript中的push()与unshift()?
push()与unshift()
方法推()和不印字()被用于在一个数组添加元素。但是它们略有差异。该方法推()是用来在添加元素端数组的,而该方法是用于在添加的元素开始的数组构成。让我们详细讨论它们。unshift()
推()
语法
array.push("element");示例
在下面的示例中,对于3元素数组,使用方法将另一个元素添加到数组的后面,结果显示在输出中。push()
<html>
<body>
<script>
var companies = ["Spacex", "Hyperloop", "Solarcity"];
document.write("推送之前:" +" "+ companies);
companies.push("Tesla");
document.write("</br>");
document.write("推送后:" +" "+ companies);
</body>
</html>输出结果
推送之前: Spacex,Hyperloop,Solarcity 推送后: Spacex,Hyperloop,Solarcity,Tesla
unshift()
语法
array.unshift("element");示例
在下面的示例中,对于3元素数组,使用unshift()方法在该数组的开头 添加另一个元素,并将结果显示在输出中。
<html>
<body>
<script>
var companies = ["Spacex", "Hyperloop", "Solarcity"];
document.write("撤离前:" +" "+ companies);
companies.unshift("Tesla");
document.write("</br>");
document.write("取消移位后:" +" "+ companies);
</script>
</body>
</html>输出结果
撤离前: Spacex,Hyperloop,Solarcity 取消移位后: Tesla,Spacex,Hyperloop,Solarcity
热门推荐
10 女神节日简短祝福语大全
11 姐姐女儿结婚祝福语简短
12 老师祝福语简短100字
13 牛年除夕祝福语简短的
14 生病祝福语简短文案
15 晚儿子生日祝福语简短
16 圣诞饭店祝福语大全简短
17 朋友孩子考试祝福语简短
18 年月日祝福语简短