I want to create a function that logs out "I have 1 bottle. I have 2 bottles. I have 3 bottles" and so on, to the console.
But I keep getting the output below:
I have 1 bottle
I have 1 bottle,bottle
I have 1 bottle,bottle,bottle
let word = []
function test() {
let x = 1
if (x <= 1) {
word.push("bottle")
console.log("I have " + x + " " + word)
} else if (x > 1) {
word.push("bottles")
console.log("I have " + x + " " + word)
}
x++
}
test()
test()
test()
2
Answers
like that ?
This is a perfect use case for a generator.
Here is a more quick-and-dirty-approach:
And here is an alternative that uses an enhanced for-loop: