I am trying to make a hangman game. So I have a function that takes the word and makes a new array of the underscore dashes. I have that working perfectly but now I am trying to add the functionality of have spacing so multiply words. But now it adds random spaces instead.
Any Help?
function dash(word) {
var dash = [];
for (var i = word.length - 1; i >= 0; i--) {
if (word[i] == " ") {
dash.push(" ");
} else {
dash.push("_");
}
}
return dash;
}
-
1can i have some input / output sample?Alongkorn– Alongkorn2016年10月15日 14:15:53 +00:00Commented Oct 15, 2016 at 14:15
5 Answers 5
This spaces aren't random – they inverted.
It's because of you running your word from back to front:
instead of for (var i = word.length - 1; i >= 0; i--) try it:
function dash(word) {
var dash = [];
for (var i = 0; i < word.length; i++) {
if (word[i] == " ") {
dash.push(" ");
} else {
dash.push("_");
}
}
return dash;
}
Comments
It's not that it's adding random spaces, it's just backwards because you're traversing the string backwards. You're starting from the end and working your way to the front of it. It works with strings consisting of a single word because you always have only that amount of spaces.
Just change
for (var i = word.length - 1; i >= 0; i--)
to
for (var i = 0; i < word.length; i++)
Here's something to run in your console to test:
function dash(word) {
var dash = [];
for (var i = 0; i < word.length; i++) {
if (word[i] == " ") {
dash.push(" ");
} else {
dash.push("_");
}
}
return dash;
}
var dashedSingle = dash('Testing');
var dashedMultiple = dash('Testing this sentence now');
console.log(dashedSingle)
console.log(dashedMultiple)
Comments
You are traversing the elements in reverse order in for loop.... i tried this and worked fine...
function dash(word) {
var dash = [];
for (var i = 0; i <=word.length - 1; i++) {
if (word[i] == " ") {
dash.push(" ");
} else {
dash.push("_");
}
}
return dash;
}
Comments
If you just want your word in an array you could use String.prototype.split to do the job for you. Then map over the character array.
var word = 'javascript is awesome'
console.log(
word.split('').map(letter => letter === ' ' ? ' ' : '_')
)
Comments
you should use ASCII value of space instead of word[i] == " "
im not sure about ASCII value of space in javascript. but dont worry you can use charCodeAt();
word[i] == charCodeAt(" ")
7 Comments
word[i] is a string, not a code.word[i] doesn't return the code, it returns the character. You would have use word.charCodeAt(i) == " ".charCodeAt(0).charCodeAt() wrong. It's a method of String, and the argument is the index.