Last active
October 1, 2015 23:57
-
-
Save webdesserts/2128569 to your computer and use it in GitHub Desktop.
How to pass values into an array - a snippet for some friends
This file contains 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
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