Skip to content

Instantly share code, notes, and snippets.

@finalcut
Created January 31, 2019 00:46
Show Gist options
  • Save finalcut/e56167f6525b228044f4d1274ced86d4 to your computer and use it in GitHub Desktop.
Save finalcut/e56167f6525b228044f4d1274ced86d4 to your computer and use it in GitHub Desktop.
Some basic array information
<html>
<head>
<script type="text/javascript">
// better way to create an array
// its easier and less prone to mistakes
var betterArray = ['summer','fall'];
//console.log(betterArray);
//console.table(betterArray);
// not a good way to create an array
// it can be confusing and lead to unexpected
// results
var worseArray = new Array(43);
//console.log(worseArray);
// function to determine the month number from the month abbrv
function whatNumberIsThisMonth(month){
var months = ['garbage','Jan','Feb'
,'Mar','Apr','May','Jun','Jul','Aug','Sep'
,'Oct','Nov','Dec'];
// show me the months
//console.table(months);
// indexOf will return -1 if it can't find the month
// remember, javascript is case sensitive so it won't find
// jan but will find Jan
return months.indexOf(month);
}
var myFamily=[];
function addAKidToMyFamily(newKid){
myFamily.push(newKid);
//dont use console in production; it is just
// a tool to help you while developing
// to help you figure out what your code is doing
console.table(myFamily);
}
function gotDivorced(person){
//find the person in the family
var index = myFamily.indexOf(person);
// if the person exists in the family remove them.
if(index !== -1){
// remember, -1 means the item wasn't in the array
// we need to know how long the myFamily array is:
var lastIndex = myFamily.length -1;
if(index === 0){
myFamily = myFamily.slice(1);
}
// removing last person, so we grab from the first
//to the next to last
else if(index === lastIndex){
myFamily = myFamily.slice(0, lastIndex-1);
}
else {
// removing someone from the middle of the array
// slice will go from the first argument index
// and then count out to the second argument number
// of indexes to get data.
var firstPart = myFamily.slice(0,index);
// slice with only one argument will start at the first
// index and then grab all the way to the end of the array
var lastPart = myFamily.slice(index+1);
// concat is an array method to concatenate two arrays into
// one resulting array.
myFamily = firstPart.concat(lastPart);
}
}
}
</script>
</head>
<body>
this is a test page for playing with arrays
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment