Skip to content

Instantly share code, notes, and snippets.

@StevenMDixon
Last active September 21, 2018 21:04
Show Gist options
  • Save StevenMDixon/9f0f8fa8c5671e9098d99860311d088b to your computer and use it in GitHub Desktop.
Save StevenMDixon/9f0f8fa8c5671e9098d99860311d088b to your computer and use it in GitHub Desktop.
// make array, there are many way, 頑張って!
var example_ = new Array(5); // outputs: [] this creates an array with a length of the parameters size.
var example_ = Array(1,2,3,5); // outputs: [1,2,3,5] this initializes the elements in the array and makes them accessible.
var example_ = [1,2,3,4]; // outputs: [1,2,3,4] //safest example for creating an array as all elements are accessible. Does not call array constructor.
var example_ = Array.of(1,2,4); // // outputs: [1,2,4] //calls the Array constructor on a list of provided elements.
// make an array from iterable objects
// this one is special because it accepts a callback as a secondary parameter which is a map function.
// this is requires ES6 support in the browser
var example_ = Array.from('foo'); //['f', 'o', 'o']
var example_ = Array.from('foo', function(l){ return l+'e'}) // ['fe', 'oe, 'oe']
// Ah the spread operator, my favorite feature
var example_ = [...'foo'] // output: ['f', 'o', 'o'] the same as calling Array.from() without the secondary argument.
// It seems we have alot of options, hmm what about converting array like and iterable objects into arrays?
// array like
// this example is a classic and was used on everything from argument lists to dom nodes.
var example_ = Array.prototype.slice.call(array-like);
// now we can use Array.from() or the spread operator to do the same. just like slice this creates a shallow copy which is great for not mutating data.
var example_ = Array.from(Arguments);
var example_ = [...Arguments];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment