I'm new to javascript so don't judge me please :)
I have a real basic string generator, but it isn't working the way I want it to, it prints a 1 letter string (e.g "c") rather than a multi-letter string
var alphabet = "abcdefghijklmnopqrstuvwxyz"
for (var i=0;i<alphabet.length;i++) {
var news = "";
news = news + alphabet[Math.floor(Math.random() * alphabet.length)]
if (i == alphabet.length - 1) {
console.log(news)
}
}
tig
28.1k10 gold badges67 silver badges99 bronze badges
-
1Please indent your code properly when posting here.jfriend00– jfriend002016年07月17日 18:23:39 +00:00Commented Jul 17, 2016 at 18:23
2 Answers 2
You have to declare and initialize the variable news outside the for loop. Declaring is not a problem when we use var to do that, because it will be hoisted to the top. But initialization is important. That has to be outside the for loop.
var alphabet="abcdefghijklmnopqrstuvwxyz";
var news="";
for (var i=0;i<alphabet.length;i++) {
news=news+alphabet[Math.floor(Math.random()*alphabet.length)]
if (i==alphabet.length-1) {
console.log(news)
}
}
answered Jul 17, 2016 at 18:16
Rajaprabhu Aravindasamy
67.2k17 gold badges107 silver badges133 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
Minor mistake. Just define var news = ''; outside for loop. (Also, use semicolons).
var alphabet="abcdefghijklmnopqrstuvwxyz";
var news="";
for (var i=0;i<alphabet.length;i++) {
news=news+alphabet[Math.floor(Math.random()*alphabet.length)]
if (i==alphabet.length-1) {
console.log(news)
}
}
answered Jul 17, 2016 at 18:20
Ashish Gupta
971 silver badge8 bronze badges
Comments
lang-js