Skip to content

Commit

Permalink
Update preallocation.md
Browse files Browse the repository at this point in the history
  • Loading branch information
Kikobeats committed Dec 30, 2017
1 parent 38ce714 commit 7f4df40
Showing 1 changed file with 18 additions and 0 deletions.
18 changes: 18 additions & 0 deletions docs/array/preallocation.md
Original file line number Diff line number Diff line change
@@ -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).
Expand Down

0 comments on commit 7f4df40

Please sign in to comment.