[afterCode] JavaScript 中如何快捷的建立一個含有相同初始值的數組

目標

function createArrayWith(length,value){...}

createArrayWith(2,3) => [3, 3]
createArrayWith(2,{test:2}) => [{test:2}, {test:2}]

條件: 儘可能的簡潔數組

首先想到的是map

function createArrayWith(length,value){
   return new Array(length).map(function(){
           return value
   })
}

失敗

createArrayWith(2,3) 
[ , ]

緣由

map calls a provided callback function once for each element in an array, in order, and constructs a new array from the results. callback is invoked only for indexes of the array which have assigned values, including undefined. It is not called for missing elements of the array (that is, indexes that have never been set, which have been deleted or which have never been assigned a value).app

from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/mapide

原來數組中的"空"元素,map(包括foreEach)都是不會去遍歷處理的. 而只傳一個參數new出來數組,每一個元素都是空的函數

死磕map

觀察Array 構造函數的接口this

new Array(element0, element1[, ...[, elementN]])
new Array(arrayLength)

能夠用不定參數的方式來建立code

用apply試試

function createArrayWith(length,value){
   return Array.apply(null,new Array(length)).map(function(){
           return value
   })
}

// 可行
createArrayWith(2,3)
[ 3, 3 ]

使用ES6的語法簡化下

function createArrayWith(length,value){
   return Array.apply(null,new Array(length)).map(()=>value)
}

createArrayWith(2,3)
[ 3, 3 ]

好像new也能夠去掉

function createArrayWith(length,value){
   return Array.apply(null,Array(length)).map(()=>value)
}

createArrayWith(2,3)
[ 3, 3 ]

到了這一步好像是最簡潔的實現方式了,可是看起來是在太怪異了.接口

ES6到底

MDNArray 方法的時候,發現了竟然有這個一個函數ip

arr.fill(value[, start = 0[, end = this.length]])

頓時草泥馬奔騰,原來ES6添加了這個新函數.element

在ES6的環境下的話,最簡潔的方式仍是get

function createArrayWith(length,value){
   return new Array(length).fill(value)
}

createArrayWith(2,3)
[ 3, 3 ]

折騰完畢

相關文章
相關標籤/搜索