Is there a function in lodash to initialize an array with default null values for a given length?
在lodash中是否有一个函数来初始化一个给定长度的默认空值的数组?
Array method currently using :
目前使用的数组方法:
var myArray = Array.apply(null, Array(myArrayLength)).map(function() { return null });
Lodash Function trying to use :
Lodash功能尝试使用:
var myArray = _.times(myArrayLength, null);
Required array :
必需的数组:
var myArray = [null, null, .......];
3 个解决方案
#1
17
That should do the tricks:
这应该做的伎俩:
_.times(arrayLength, _.constant(null));
eg:
例如:
_.times(5, _.constant(null));
[null, null, null, null, null]
#2
6
_.fill(Array(arrayLength), null);
eg:
例如:
_.fill(Array(5), null); // [ null, null, null, null, null ]
#3
4
I'd suggest using _.fill
我建议使用_.fill
_.fill(Array(myArrayLength), null);`
It seems to be faster than _.times
, at least it is on Chrome.
它似乎比_时间更快,至少它在Chrome上。
See perf comparison here: https://jsperf.com/fill-vs-times/1
请参阅此处的性能比较:https://jsperf.com/fill-vs-times/1
#1
17
That should do the tricks:
这应该做的伎俩:
_.times(arrayLength, _.constant(null));
eg:
例如:
_.times(5, _.constant(null));
[null, null, null, null, null]
#2
6
_.fill(Array(arrayLength), null);
eg:
例如:
_.fill(Array(5), null); // [ null, null, null, null, null ]
#3
4
I'd suggest using _.fill
我建议使用_.fill
_.fill(Array(myArrayLength), null);`
It seems to be faster than _.times
, at least it is on Chrome.
它似乎比_时间更快,至少它在Chrome上。
See perf comparison here: https://jsperf.com/fill-vs-times/1
请参阅此处的性能比较:https://jsperf.com/fill-vs-times/1