6.3: Loops with Arrays
Last updated
var letters = ['a', 'b', 'c'];
letters.length; // This returns 3, the number of elements in letters// Index starts at 0, representing the 0th index of the array
var index = 0;
// We will iterate over the letters array
var letters = ['a', 'b', 'c'];
// Run the loop while index is less than the length of the array
while (index < letters.length) {
// letters[index] represents a different element for each loop iteration
var currentLoopLetter = letters[index];
// Log the current element in each iteration
console.log(currentLoopLetter);
// Increment the index at the end of each iteration
index = index + 1;
}// Initialise an empty names array
var names = [];
var main = function (input) {
// Set a boolean value found to a default value of false
var found = false;
// Loop over the names array, and set found to true if the input name already
// exists in the names array
var index = 0;
while (index < names.length) {
var currentName = names[index];
if (currentName == input) {
found = true;
}
index = index + 1;
}
// If no duplicate name was found, add the input name to the names array
if (!found) {
names.push(input);
}
// Return the full array of names
var myOutputValue = 'All names: ' + names;
return myOutputValue;
};