Reputation: 151
I want my for loop to print out every item in the array, not just the last item. Cant figure out where I'm going wrong:
var patients = ["Julia", "Kelly", "Thomas", "Clare"];
function lineOfPatients(line) {
if (!line.length) {
return "Empty"
}
for(var i = 0; i < line.length; i++) {
var list = `${i + 1}. ${line[i]},`
}
return `The line is currently: ${list}`
}
lineOfPatients(patients)
This returns "The line is currently: 4. Clare,"
I want it to return "The line is currently: 1. Julia, 2. Kelly, 3. Thomas, 4. Clare"
Upvotes: 1
Views: 2964
Reputation: 23
Here's what you want. (Got carried away with code golf)
const patients = ["Julia", "Kelly", "Thomas", "Clare"]
const lineOfPatients = (line) => "The line is currently: " + (!line || !line.length) ? "Empty" : line.map((patient, idx) => `${idx + 1}. ${patient}`).join(', ')
console.log(lineOfPatients(patients))
The reason it's not working is because your redeclaring the variable list
on every loop. Even if you moved it out of the loop, your not appending the output from the for-loop, your assigning it. It will always be the output from the last loop.
Upvotes: 1
Reputation: 3578
var list
is being declared inside your loop. This means that it is being recreated with a new value on each itteration. Declare this variable outside of the loop, as an array. E.g,
var list = new Array();
Then, in your loop, add to the array;
list[i] = .....
Upvotes: 0
Reputation: 49
The problem with your code is that with each iteration of your for-loop, you redeclare var list = `${i + 1}. ${line[i]},`
so that by the time you return, list
only equals the last element in the array.
You could do this:
function lineOfPatients(line) {
if (!line.length) {
return "Empty"
}
var returnString = "The line is currently: "
for(let i = 0; i < line.length; i++) {
let patient = ` ${i + 1}. ${line[i]},`;
returnString += patient;
}
return returnString;
}
Upvotes: 1
Reputation: 2047
You can call join
method on lines
array which will contain your lines.
var patients = ["Julia", "Kelly", "Thomas", "Clare"];
function lineOfPatients(line) {
if (!line.length) {
return "Empty";
}
var lines = [];
for(var i = 0; i < line.length; i++) {
var list = `${i + 1}. ${line[i]}`
lines.push(list)
}
return `The line is currently: ${lines.join(", ")}`
}
console.log(lineOfPatients(patients))
Upvotes: 2
Reputation: 11136
Your issue is that you are reassigning the list
variable each time through the loop, so you are overwriting the previous value.
To avoid this, use the +=
operator instead of the =
operator like so:
var patients = ["Julia", "Kelly", "Thomas", "Clare"];
function lineOfPatients(line) {
if (!line.length) {
return "Empty"
}
var list = "";
for(var i = 0; i < line.length; i++) {
list += `${i + 1}. ${line[i]}, `
}
return `The line is currently: ${list}`
}
console.log(lineOfPatients(patients))
Upvotes: 2