简体   繁体   中英

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. 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

 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.

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

console.log(makeRectangle(5, 6))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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