简体   繁体   English

在 Javascript 中使用换行符的问题

[英]Problem using the Newline Character in Javascript

I'm trying to write a function which will return a rectangle of *'s.我正在尝试编写一个函数,它将返回一个 * 的矩形。 It keeps throwing up an error whenever I try to use \\n.每当我尝试使用 \\n 时,它都会不断抛出错误。 I assume i'm using it incorrectly but don't know how - can anyone help?我假设我使用它不正确但不知道如何 - 任何人都可以帮忙吗?

function makeRectangle(m, n) {
    return '*'.repeat(m) \n.repeat(n);
}

You must concat \\n using + operator before next repeat您必须在下一次重复之前使用+运算符连接\\n

 function makeRectangle(m, n) { return ("*".repeat(m) + "\\n").repeat(n) } console.log(makeRectangle(3, 4))

The newline needs to be enclosed as a string:换行符需要作为字符串括起来:

function makeRectangle(m, n) {
    return ('*'.repeat(m) + '\n').repeat(n);
}

or just for fun, a string literal version, to eliminate the '\\n' entirely.或者只是为了好玩,一个字符串文字版本,完全消除 '\\n'。

function makeRectangle(m, n) {
    return `${`${'*'.repeat(m)}
`.repeat(n)}`;
}

console.log(makeRectangle(5, 6))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM