這篇文章跟大家介紹一下JavaScript中將元素加入到陣列開頭的3種方法。有一定的參考價值,有需要的朋友可以參考一下,希望對大家有幫助。
今天,我們來一起學習如何把元素加入到陣列的開頭。
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/
#作者:Orkhan Jafarov
翻譯地址:https://segmentfault.com/a/1190000039129785
更多程式相關知識,請造訪:程式設計影片! !
以上是詳解JavaScript數組開頭添加元素的3種方法的詳細內容。更多資訊請關注PHP中文網其他相關文章!