Javascript字符串问题 [英] Javascript String Question

查看:84
本文介绍了Javascript字符串问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试用一个名为''makex''的函数编写一个JS程序。此函数应接受一个参数,然后返回一个字符串,该字符串重复字母X的次数与参数一样多。

例如,如果我调用makex(5)它应该输出XXXXX(5 X'' S)。到目前为止,这是我的代码:

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:

function makex(howMany)
{ 
  console.log("The parameter was "+howMany);
  for(var x = 0; x <= howMany; x++)
  {
   console.log(x); 
  }
}
  
console.log(makex(5));

推荐答案

试试这个:

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

  var strBuf = '';

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

  return strBuf;
}


尝试

Try
function makex(howMany)
{
console.log("The parameter was "+howMany);
string t;

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





如果你想让字母动态即允许任何字母而不只是X,试试



If you want to make the letter dynamic i.e. allow any letter instead of just X, try

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);
}


这篇关于Javascript字符串问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆