When tracing out variables in the console, How to create a new line?

所以我尝试做一些简单的事情,我想把我在控制台中的跟踪分成几行,使用1 console. log 语句:

console.log('roleName = '+roleName+' role_ID = '+role_ID+' modal_ID = '+modal_ID+\n+'related = '+related);

How would you write the above to trace out the following?

roleName = test
role_ID = test
modal_UD = test
related = test

instead of roleName = test role_ID = test modal_UD = test related = test

我已经检查了其他几个看起来相似的问题,但没有一个有帮助或正在谈论一件不同的事情。

谢谢你帮我看!

136428 次浏览

Easy, \n needs to be in the string.

你应该把它包括在引号 '\n'中,见下文,

console.log('roleName = '+roleName+ '\n' +
'role_ID = '+role_ID+  '\n' +
'modal_ID = '+modal_ID+ '\n' +
'related = '+related);

您需要添加新的行字符 \n:

console.log('line one \nline two')

会显示:

一号线

二号线

为什么不对每个变量使用单独的 console.log(),并用逗号分隔,而不是将它们全部转换为字符串呢?这将给出单独的行,并给出每个变量的真值,而不是每个变量的字符串表示形式(假设它们可能不全是字符串)。

console.log('roleName',roleName);
console.log('role_ID',role_ID);
console.log('modal_ID',modal_ID);
console.log('related',related);

我觉得这样更容易阅读和维护。

最糟糕的是

console.log({'some stuff': 2} + '\n' + 'something')

是所有的东西都被转换成字符串,如果你需要对象来显示,你可以看下面:

[object Object]

Thus my variant is the next code:

console.log({'some stuff': 2},'\n' + 'something');
console.log('Hello, \n' +
'Text under your Header\n' +
'-------------------------\n' +
'More Text\n' +
'Moree Text\n' +
'Moooooer Text\n' );

这对我的工作只有文字,很容易的眼睛。

在 ES6/ES2015中,可以使用名为 template literals的字符串文本语法。模板字符串使用反勾字符代替单引号’或双引号”。它们还保留了新的行和制表符

const roleName = 'test1';
const role_ID = 'test2';
const modal_ID = 'test3';
const related = 'test4';
        

console.log(`
roleName = ${roleName}
role_ID = ${role_ID}
modal_ID = ${modal_ID}
related = ${related}
`);

You may use multiline template literals, but you'll need to break formatting to avoid unneeded whitespace at the beginning of each line:

const roleName = 'Read';
const role_ID = '887623';
const modal_ID = '346433';
const related = 'related';


function foo() {
if (true) {
if (true) {
console.log(
`roleName = ${roleName}
role_ID = ${role_ID}
modal_ID = ${modal_ID}
related = ${related}`
);
}
}
}


foo();


function bar() {
if (true) {
if (true) {
console.log(
`roleName = ${roleName}
role_ID = ${role_ID}
modal_ID = ${modal_ID}
related = ${related}`
);
}
}
}


bar();

Instead, you may put your strings to array and call .join('\n'):

const roleName = 'Read';
const role_ID = '887623';
const modal_ID = '346433';
const related = 'related';


console.log([
`roleName = ${roleName}`,
`role_ID = ${role_ID}`,
`modal_ID = ${modal_ID}`,
`related = ${related}`
].join('\n')
)