Skip to content

Instantly share code, notes, and snippets.

@jergason
Created May 23, 2014 17:22
Show Gist options
  • Select an option

  • Save jergason/19d44cf89351de60059d to your computer and use it in GitHub Desktop.

Select an option

Save jergason/19d44cf89351de60059d to your computer and use it in GitHub Desktop.
A use for the Array() constructor!
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; });
}
@iammerrick
Copy link
Copy Markdown

@iammerrick
Copy link
Copy Markdown

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...

@jergason
Copy link
Copy Markdown
Author

Ah, that makes sense.

@iammerrick
Copy link
Copy Markdown

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