console.log 使用什么将其转换为字符串?

What does console.log use to convert this to string?

提问人:Alk 提问时间:8/5/2022 更新时间:8/6/2022 访问量:583

问:

什么用于将变量转换为字符串?console.log

 console.log('DEBUGGING', this, JSON.stringify(this), String(this), this.toString(), `${this}`);

我正在记录上述内容并收到:

DEBUGGING restaurant undefined class extends Model {} class extends Model {} class extends Model

我需要将字符串保存到变量中,但是只记录这一点 - 转换为字符串的所有其他方法都会产生对我来说无用的。restaurantconsole.logclass extends Model {}

JavaScript 节点 .js 控制台.log

评论

0赞 0xLogN 8/5/2022
请让您的运行时更清晰。Node.js 使用 ,但我不确定 Web 浏览器。util.inspect()
0赞 Alk 8/5/2022
我在节点中运行这个。
0赞 Alk 8/5/2022
@0xLogN有效!如果您想将其作为答案发布,我很乐意接受。util.inspect()

答:

1赞 0xLogN 8/6/2022 #1

根据评论,我被告知这是 Node。OP,请将其包含在将来的问题中!

如果我要编写自己的console.log实现,它可能类似于以下内容:

const util = require('util');
console.log = function log(...params) {
    process.stdout.write(params.map(v => typeof v === 'string' ? v : util.inspect(v)) + '\n');
}

注意到util.inspect()了吗?这就是魔力。您可以通过单击文档链接(与之前的链接相同)来阅读它。