Skip to content

Instantly share code, notes, and snippets.

@webdesserts
Last active October 1, 2015 23:57
Show Gist options
  • Save webdesserts/2128569 to your computer and use it in GitHub Desktop.
Save webdesserts/2128569 to your computer and use it in GitHub Desktop.
How to pass values into an array - a snippet for some friends
var array = []
array[1] = "a value"
array[2] = "a new value"
console.log(array) // returns ["a value","a new value"]
// p.s. console.log() and alert() are interchangeable. If you use console.log the
// message appears in your browser's console rather than in a popup.
// That's kinda obvious but here's something your probably haven't used yet:
/* Array.push()
is a JavaScript method that allows you to tack a value on the end of an array. */
array.push(1)
array.push(2)
array.push(3)
console.log(array) // returns [1,2,3]
// you can also pass multiple values
array.push(4,5,6)
console.log(array) // returns [1,2,3,4,5,6]
// This makes it easy to populate an array without having to do some complicated
// looping or something like that.
// There are a lot of other helpful Array Methods as well:
/* Array.pop()
removes the last value of the array and returns it. */
var giveItBack = array.pop()
console.log(array) // returns [1,2,3,4,5]
console.log(giveItBack) // returns 6
/* Array.length()
returns the number of items in an array */
array = [1,2,3,4,5]
console.log(newArray.length()) // returns 5
/* Array.join()
concatenates all items in an array with the separator provided */
array = [1,2,3,4,5,6]
array.join() // returns "123456"
array.join(",") // returns "1,2,3,4,5,6"
array.join(" and ") // returns "1 and 2 and 3 and 4 and 5 and 6"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment