算法挑战:重复字符串

时间:2019-06-20 03:53:30

标签: javascript

仅学习JS并经历算法挑战。

下面的代码应重复一个字符串(str)x(num)次。

因此,例如repeatStringNumTimes('*',3)应该为'***'。 下面的代码可以做到这一点...但是在输出的开头出现了一个“未定义”的单词。这是为什么?!我已经定义了所有变量...

function repeatStringNumTimes(str, num) {

    let len = str.length;
    let string;

for (let i = 0; i < num; i++) {

    for (let x = 0; x < len; x++) {

        string += str[x];

    }

}
return string;
}

console.log(repeatStringNumTimes('*', 10));

4 个答案:

答案 0 :(得分:4)

  

我已经定义了所有变量

是的,您定义,但没有初始化

javascript中的默认初始化为 ** Missing executable /usr/lib/jvm/adoptopenjdk-11-jdk- openj9/bin/jcmd even though man page /usr/lib/jvm/adoptopenjdk- 11-jdk-openj9/man/man1/jcmd.1.gz exists. ** This is probably a bug in AdoptOpenJDK and should be reported upstream. ** Missing executable /usr/lib/jvm/adoptopenjdk-11-jdk- openj9/bin/jinfo even though man page /usr/lib/jvm/adoptopenjdk- 11-jdk-openj9/man/man1/jinfo.1.gz exists. ** This is probably a bug in AdoptOpenJDK and should be reported upstream. ** Missing executable /usr/lib/jvm/adoptopenjdk-11-jdk- openj9/bin/jmap even though man page /usr/lib/jvm/adoptopenjdk- 11-jdk-openj9/man/man1/jmap.1.gz exists. ** This is probably a bug in AdoptOpenJDK and should be reported upstream. ** Missing executable /usr/lib/jvm/adoptopenjdk-11-jdk- openj9/bin/jstat even though man page /usr/lib/jvm/adoptopenjdk- 11-jdk-openj9/man/man1/jstat.1.gz exists. ** This is probably a bug in AdoptOpenJDK and should be reported upstream. ** Missing executable /usr/lib/jvm/adoptopenjdk-11-jdk- openj9/bin/jstatd even though man page /usr/lib/jvm/adoptopenjdk-11-jdk-openj9/man/man1/jstatd.1.gz exists. ** This is probably a bug in AdoptOpenJDK and should be reported upstream.

因此,undefined等于let a;
您应该使用空字符串初始化您的字符串:

let a = undefined;

只是一个注释:

现代javascript引擎具有用于该任务的String.prototype.repeat方法:

let string = '';  

答案 1 :(得分:1)

您可能需要声明字符串:

let string = "";

更新:

因为这行:

string += str[x];

等于:

string = string + str[x]; 
// equivalent to string = undefined + str[x]

您正在为其分配一个未定义的字符串(+ str [x])。

答案 2 :(得分:0)

好的,为了完成这项工作,我添加了

let string = "";

我不确定为什么会这样。来自经验丰富的人士的任何见解将不胜感激。

答案 3 :(得分:0)

使用while

的传统方法

const repeatStringNumTimes = (str, num) => {
  let res = str
  while (--num) res += str
  return res
}

console.log(repeatStringNumTimes('*', 10))

使用String.prototype.repeat

const repeatStringNumTimes = (str, num) => str.repeat(num)

console.log(repeatStringNumTimes('*', 10))

使用String.prototype.padStart()String.prototype.padEnd()

const repeatStringNumTimes = (str, num) => ''.padStart(num, str)

console.log(repeatStringNumTimes('*', 10))

使用Array.prototype.join()

const repeatStringNumTimes = (str, num) => Array(num).join(str)

console.log(repeatStringNumTimes('*', 10))