Created
May 23, 2014 17:22
-
-
Save jergason/19d44cf89351de60059d to your computer and use it in GitHub Desktop.
A use for the Array() constructor!
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| function makeN(n, obj) { | |
| // gotta use .apply(null) because Array(n) makes a new empty array of size n and map behaves starngely | |
| // Array.apply(null, Array(n)) creates an array of size n with undefined as the value of every item | |
| // we can then call map on it to get back an array with n `obj`s. | |
| return Array.apply(null, Array(n)).map(function() { return obj; }); | |
| } |
It is only called for elements of the array which actually exists, this gotcha exists for forEach as well.
Array(10).forEach(function(){ console.log('hi'); });
Silence...
Author
Ah, that makes sense.
Also... Traceur/ES6 http://jsbin.com/vayayevo/1/edit
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
http://cl.ly/image/0r3V1W2o0l0d