[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 ]

折腾完毕

相关文章
相关标签/搜索