Reputation: 1388
I have users inputting letters a single char into a time through an input field. Each char is taken and saved into an array called rightLtrsArr
.
What I need to do is take all the letters that are stored in that array as separate elements and make them into a string. The string would be updated for each letter the user enters. Since I know I can't push a new char into a string, but would have to concatenate two strings together to create a new one, I've been trying to do this through a loop like so:
for (var i = 0; i < rightLtrsArr.length; i ++){
guessedWord = rightLtrsArr.concat([i]);
console.log("the guessed word is " + guessedWord);
}
Needless to say, this hasn't worked out so well. Is my syntax wrong? What am I missing here?
Upvotes: 0
Views: 1563
Reputation: 366
There's a shortcut to do what you want:
rightLtrsArr.join('')
.join() combines joins all of the elements of an array into a string. As for a solution more like yours, you should start with an empty string and append it.
var guessedWord = "";
for (var i = 0; i < rightLtrsArr.length; i ++){
guessedWord += rightLtrsArr[i];
};
console.log("the guessed word is " + guessedWord);
Upvotes: 0
Reputation: 10765
Declare a variable, and then append to that in your loop.
let guessedWord = "";
for(let i = 0; i < rightLtrsArr.length; i++){
guessedWord += rightLtrsArr[i];
}
console.log("the guessed word is " + guessedWord);
Upvotes: 0
Reputation: 674
If you want to concatenate the characters in your array you might need to do something like:
for (var i = 0; i < rightLtrsArr.length; i ++){
guessedWord += rightLtrsArr[i];
}
console.log("the guessed word is " + guessedWord);
I am not familiar with the .concat()
function but please let me know if this works.
Check this fiddle out.
Upvotes: 0
Reputation: 23955
Something like this?
rightLtrsArr = ['a','b','c']
guessedWord = '';
for (var i = 0; i < rightLtrsArr.length; i ++){
guessedWord = guessedWord.concat(rightLtrsArr[i]);
}
console.log("the guessed word is " + guessedWord);
// Alternative:
// console.log("the guessed word is " + rightLtrsArr.join(''));
Upvotes: 0
Reputation: 3879
You can use the useful JavaScript function called join
that is made for just this purpose - joining an array. You can use it like this:
let rightLtrsArr = ['h', 'e', 'l', 'l', 'o'];
let guessedWord = rightLtrsArr.join('');
console.log("the guessed word is " + guessedWord);
Note: The parameter is what to separate the elements by - in this case we don't want to separate them so we pass an empty string.
Note 2: You can use this function to join not only single characters but any array.
Upvotes: 3