简体   繁体   中英

Lodash/underscore function to Initialize an array with default null values of a given length

Is there a function in lodash to initialize an array with default null values for a given length?

Array method currently using :

     var myArray = Array.apply(null, Array(myArrayLength)).map(function() { return null });

Lodash Function trying to use :

     var myArray = _.times(myArrayLength, null);

Required array :

  var myArray = [null, null, .......];

That should do the tricks:

_.times(arrayLength, _.constant(null));

eg:

_.times(5, _.constant(null));
[null, null, null, null, null]
_.fill(Array(arrayLength), null)

// exemple:
_.fill(Array(5), null); // [ null, null, null, null, null ]

EDIT:

I made some performance tests: https://jsperf.com/lodash-initialize-array-fill-vs-times

  • _.fill is faster than _.times
  • null is faster than _constant(null)

I'd suggest using _.fill

_.fill(Array(myArrayLength), null);`

It seems to be faster than _.times , at least it is on Chrome.

See perf comparison here: https://jsperf.com/fill-vs-times/1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM