Exercises: Arrays
- Create an array to hold your top choices (colors, food, whatever).
- For each choice, log to the screen a string like: "My #1 choice is blue."
- Bonus: Change it to log "My 1st choice, "My 2nd choice", "My 3rd choice", picking
the right suffix for the number based on what it is.
var choices = ['red', 'orange', 'pink', 'yellow'];
for (var i = 0; i < choices.length; i++) {
console.log('My #' + (i + 1) + ' choice is ' + choices[i]);
}
for (var i = 0; i < choices.length; i++) {
var choiceNum = i + 1;
var choiceNumSuffix;
if (choiceNum == 1) {
choiceNumSuffix = 'st';
} else if (choiceNum == 2) {
choiceNumSuffix = 'nd';
} else if (choiceNum == 3) {
choiceNumSuffix = 'rd';
} else {
choiceNumSuffix = 'th';
}
console.log('My ' + choiceNum + choiceNumSuffix + ' choice is ' + choices[i]);
}
- Write a JavaScript function called first() that takes one input, an array, and returns the first element in that array
- Write another JavaScript function called last() that takes one input, an array, and returns the lastt element in that array
function first(array) {
return array[0];
}
function last(array) {
return array[array.length - 1];
}
- Given an array of strings, find the longest string and print out that string.
- hint: strings also have the .length property - i.e `"starburst".length` is 9
var strings = ["word", "wordier", "wordiest", "foo"];
var longestString = "";
for(var i = 0; i < strings.length; i++) {
var currentString = strings[i];
if(currentString.length > longestString.length) {
longestString = currentString;
}
}
console.log("The longest string is " + longestString + ". It has " + longestString.length + " letters.");