JavaScript 中的 Push() 对比 unshift()?


push() 对比 unshift()

push() unshift() 方法用于向数组中添加元素。但它们有细微差别。方法 push() 用于在数组的末尾添加元素,而方法 unshift() 用于在数组的开头添加元素。让我们详细讨论一下它们。

push()

语法

array.push("element");

示例

在以下示例中,使用 push() 方法向一个 3 元素数组的末尾添加另一个元素,并在输出中显示结果。

<html>
<body>
<script>
   var companies = ["Spacex", "Hyperloop", "Solarcity"];
   document.write("Before push:" +" "+ companies);
   companies.push("Tesla");
   document.write("</br>");
   document.write("After push:" +" "+ companies);
</body>
</html>

输出

Before push: Spacex,Hyperloop,Solarcity
After push: Spacex,Hyperloop,Solarcity,Tesla

unshift()

语法

array.unshift("element");

示例

在以下示例中,使用 unshift() 方法向一个 3 元素数组的开头添加另一个元素,并在输出中显示结果。

<html>
<body>
<script>
   var companies = ["Spacex", "Hyperloop", "Solarcity"];
   document.write("Before unshift:" +" "+ companies);
   companies.unshift("Tesla");
   document.write("</br>");
   document.write("After unshift:" +" "+ companies);
</script>
</body>
</html>

输出

Before unshift: Spacex,Hyperloop,Solarcity
After unshift: Tesla,Spacex,Hyperloop,Solarcity

更新于: 19-Aug-2019

256 次浏览

开启你的 职业生涯

完成课程认证

开始学习
广告
© . All rights reserved.