[afterCode] JavaScript 中如何快捷的创建一个含有相同初始值的数组

本文探讨了使用JavaScript创建固定长度并填充特定值的数组的方法。从最初尝试使用map方法遇到问题,到利用ES6的fill方法实现简洁高效的目标。

目标

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).

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

原来数组中的"空"元素,map(包括foreEach)都是不会去遍历处理的. 而只传一个参数new出来数组,每个元素都是空的

死磕map

观察Array 构造函数的接口

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

可以用不定参数的方式来创建

用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 方法的时候,发现了居然有这个一个函数

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

顿时草泥马奔腾,原来ES6添加了这个新函数.

在ES6的环境下的话,最简洁的方式还是

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

createArrayWith(2,3)
[ 3, 3 ]

折腾完毕

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值