Reputation: 1
I'm trying to double my string xyz to xxyyzz in JS but can't get it to return correctly. What am I doing wrong?
<script>
string=["xyz"];
for (var i=0;i<string.length;i++)
{
document.write(string[i]*2);
}
</script>
Upvotes: 0
Views: 939
Reputation: 13425
You didn't declared a string, you declared an array of string with 1-length.
Your are multiplying position of array (string[i]*2
), trying concatenating (string[i] + string[i]
).
This should work:
var string = 'xyz';
for (var i = 0, len = string.length; i < len; i++) {
document.write(string[i] + string[i]);
}
Upvotes: 0
Reputation: 188
A few problems:
string
inside an array, giving string.length
a value of 1 as that's the number of elementsHere's how I'd do it:
var string = "xyz";
var newString = "";
for (var i = 0; i < string.length; i++)
newString += string[i] + string[i];
document.write(newString);
Upvotes: 0
Reputation: 33409
var string = "xyz".split('').map(function(s){return s+s}).join('');
I like doing it using array maps instead of for loops. It seems cleaner to me.
Upvotes: 4
Reputation: 816
The correct way would be to add the strings together (concatenation) instead of using a multiply by 2 which won't work. See below:
<script type="text/javascript">
var string = ['xyz'];
for (var i = 0, len = string.length; i < len; i++) {
document.write(string[i] + string[i]);
}
</script>
Upvotes: 0