Click here to Skip to main content
15,903,724 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'm trying to write a JS program with a function called 'makex'. This function should accept a parameter and then return a string that repeats the letter X as many times as the parameter.
For example, if I called makex(5) it should output XXXXX (5 X's). Here's my code so far:
JavaScript
function makex(howMany)
{ 
  console.log("The parameter was "+howMany);
  for(var x = 0; x <= howMany; x++)
  {
   console.log(x); 
  }
}
  
console.log(makex(5));
Posted
v2
Comments
Matej Hlatky 11-Apr-13 5:36am    
homework? :)
dteece1 11-Apr-13 5:37am    
Sort of, it's work I want to finish from earlier today. I've thought about it, but I can't figure it out.

Try this:
JavaScript
function makex(howMany) {
  if (howMany < 0)
    throw new RangeError("Invalid string length");

  var strBuf = '';

  while (howMany--)
    strBuf += "x";

  return strBuf;
}
 
Share this answer
 
Comments
dteece1 11-Apr-13 5:50am    
Oh right, I didn't know you could use the value of howMany decrementing for a "while" condition.
In any case, this worked. Thank you very much
Try
C#
function makex(howMany)
{
console.log("The parameter was "+howMany);
string t;

for(var x = 0; x <= howMany; x++)
{
  t = t + 'X';
}
console.log(x);
}


If you want to make the letter dynamic i.e. allow any letter instead of just X, try
C#
function makex(howMany, text)
{
console.log(&quot;The parameter was &quot;+howMany);
string t = t + 'X';

for(var x = 0; x &lt;= howMany; x++)
{
  t = t + text;
}
console.log(x);
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900