Question
In its current form, disc_3.js contains three errors having to do with arrays, loops, and if statements. For this discussion, please do the following: 1)
In its current form, disc_3.js contains three errors having to do with arrays, loops, and if statements. For this discussion, please do the following: 1) Identify all three errors 2) Explain why the errors prevent the code from working 3) Provide solutions to each error
Discussion 3
Favorite Cars
Enter your four favorite cars into the textbox.
Content of disc_3.js:
// This program uses an array to store a list of favorite car makes and then // outputs the contents to an HTML page.
var cars; // Array to hold car makes (Error 1: not an array) var i = 0; // Index
// The addCar() function will add a car from the textbox to the cars[] array. // The array is output once it contains 4 entries. function addCar() { if (i < 4) { cars[i] = input.value; input.value = ""; i++; if (i = 4) { // Error 2: assignment instead of comparison displayCars(); } } }
// The displayCars() function uses a for loop to loop through the cars[] array // and output its contents to the
element with ID "output" function displayCars() { // Reference the element with ID "output" for simpler code var output = document.getElementById("output");
output.innerHTML += "Your list is: "; for (var j = 1; j < cars.length; j++) { // Error 3: j should start at 0 output.innerHTML += cars[j]; if (j < cars.length - 1) output.innerHTML += ", "; } }
// Backward compatible event listener if (document.getElementById("submit").addEventListener) { document.getElementById("submit").addEventListener("click", addCar, false); } else if (document.getElementById("submit").attachEvent) { document.getElementById("submit").attachEvent("onclick", addCar); }
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started