From 7f4df400b54932ccfec43a0ced0bacacfafcc8dc Mon Sep 17 00:00:00 2001 From: Kiko Beats Date: Sat, 30 Dec 2017 11:23:43 +0100 Subject: [PATCH] Update preallocation.md --- docs/array/preallocation.md | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/docs/array/preallocation.md b/docs/array/preallocation.md index 681a314..8496693 100644 --- a/docs/array/preallocation.md +++ b/docs/array/preallocation.md @@ -1,5 +1,23 @@ # Preallocation +## Initialize value + +If you want to preallocate an array with a initial value, you can use [`Array.prototype.fill()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/fill): + +```js +const n = 4 +const array = Array(0).fill(0) // [ 0, 0, 0, 0 ] +``` + +Sometimes is useful initialize an array with a range of index. A tricky way to do that could be: + +```js +const n = 4 +const array = Array.from(Array(N).keys()) // [ 0, 1, 2, 3, 4 ] +``` + +## Reusing instances + It's typical to use an `Array` as a temporal container of data. !> If you need to work with binary data, use a [Buffer](https://www.npmjs.com/package/buffer).