1
0
mirror of https://github.com/jbranchaud/til synced 2026-01-03 23:28:02 +00:00

Add Create An Array Containing 1 To N as a javascript til.

This commit is contained in:
jbranchaud
2015-12-29 11:52:03 -06:00
parent 9c2b97b014
commit 5328b42b2f
2 changed files with 36 additions and 0 deletions

View File

@@ -99,6 +99,7 @@ smart people at [Hashrocket](http://hashrocket.com/).
### javascript ### javascript
- [Character Codes from Keyboard Listeners](javascript/character-codes-from-keyboard-listeners.md) - [Character Codes from Keyboard Listeners](javascript/character-codes-from-keyboard-listeners.md)
- [Create An Array Containing 1 To N](javascript/create-an-array-containing-1-to-n.md)
- [Splat Arguments To A Function](javascript/splat-arguments-to-a-function.md) - [Splat Arguments To A Function](javascript/splat-arguments-to-a-function.md)
- [Throttling A Function Call](javascript/throttling-a-function-call.md) - [Throttling A Function Call](javascript/throttling-a-function-call.md)
- [Truthiness of Integer Arrays](javascript/truthiness-of-integer-arrays.md) - [Truthiness of Integer Arrays](javascript/truthiness-of-integer-arrays.md)

View File

@@ -0,0 +1,35 @@
# Create An Array Containing 1 To N
Some languages, such as Ruby, have a built in range constraint that makes it
easy to construct an array of values from 1 to N. JavaScript is not one of
those languages. Nevertheless, if you don't mind the aesthetics, you can get
away with something like this:
```javascript
> Array.apply(null, {length: 10}).map(Number.call, Number);
=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
```
That gives us `0` through `9`. To get `1` through `10`, we can tweak it
slightly:
```javascript
> Array.apply(null, {length: 10}).map(Number.call, function(n) {
return Number(n) + 1;
});
=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
```
To generalize this, we can replace `10` with `N` and then just expect that
`N` will be defined somewhere:
```javascript
> var N = 10;
=> undefined
> Array.apply(null, {length: N}).map(Number.call, function(n) {
return Number(n) + 1;
});
=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
```
[Source](http://stackoverflow.com/a/20066663/535590)