Reputation: 1
I have an assignment in school where we should grab a text string taken from a promt and then let an alert print the text string 10 times. But we have to use a for-loop. But I can't seem to get it to work even though I read all the pages covering this.
function buttonAction7() {
var someMsg = prompt("Write something");
for(var i = 0; i < 10; i++){
someMsg+someMsg;
}
alert(someMsg);
}
Upvotes: 0
Views: 3803
Reputation: 49
Try this.
var someMsg=prompt("Write Something");
var i;
for(i=0;i<10;i++){
alert(someMsg);
}
Upvotes: 0
Reputation: 56
If i understand what you're asking, you want the alert to display the string 10 times back to back in the same alert window? (like "Write somethingWrite somethingWrite something..."):
If that is correct then your issue is your computation inside your for loop. You are simply add the two strings together, but doing nothing with the result. You need to save the result back to the someMsg variable on each loop iteration, like this:
var someMsg = promt("Write something");
var output = "";
for(var i=0; i<10; i++) {
output = output + someMsg;
}
alert(output);
You see how the result of output+someMsg is being saved back to the variable output with each iteration. You can also write that short hand like this:
output += someMsg;
Upvotes: 2
Reputation: 91598
The statement:
someMsg+someMsg;
Doesn't actually do anything, it just returns a logical value. You'll probably want to assign this value to something, such as:
someMsg = someMsg + someMsg; // Notice assignment operator, we're now actually modifying the value of someMsg
If you wanted to build a string with the message 10 times, you'd probably want something more like:
var someMsg = prompt("Write something");
var msg = '';
for(var i = 0; i < 10; i++)
{
msg += someMsg + '\n'; // Add a line break after each iteration
}
window.alert(msg);
Upvotes: 5