本篇文章為大家介紹JavaScript中往陣列開頭新增元素的方法。有一定的參考價值,有需要的朋友可以參考一下,希望對大家有幫助。
今天,我們來一起學習如何把元素加入元素的首個元素。
let fruits = ["Apple", "Banana", "Mango"]; fruits.unshift("Orange"); console.log(fruits); // Prints ["Orange", "Apple", "Banana", "Mango"] fruits.unshift("Guava", "Papaya"); console.log(fruits); // Prints ["Guava", "Papaya", "Orange", "Apple", "Banana", "Mango"]
var fruits = ["Apple", "Banana", "Mango"]; var moreFruits = ["Orange", ...fruits]; console.log(moreFruits); // Prints ["Orange", "Apple", "Banana", "Mango"] var someoMoreFruits = ["Guava", "Papaya", ...moreFruits]; console.log(someoMoreFruits); // Prints ["Guava", "Papaya", "Orange", "Apple", "Banana", "Mango"] console.log(fruits); // Prints ["Apple", "Banana", "Mango"]
我們也可以使用concat()
方法在開頭連接兩個(或更多)陣列。
var fruits = ["Apple", "Banana", "Mango"]; var moreFruits = ["Orange"]; var someoMoreFruits = ["Guava", "Papaya"]; var allFruits = someoMoreFruits.concat(moreFruits, fruits); console.log(allFruits); // Prints ["Guava", "Papaya", "Orange", "Apple", "Banana", "Mango"]
原文網址:https://codingnconcepts.com/javascript/how-to-add-element-at-beggining-of-javascript-array/
#更多程式相關知識,請造訪:程式設計影片! !
以上是淺談JavaScript中往數組開頭新增元素的幾種方法的詳細內容。更多資訊請關注PHP中文網其他相關文章!