繁体   English   中英

console.log(String(console.log('Not undefined'))==='未定义'); console.log(String(console.log('Not undefined'))!=='Not undefined');

[英]console.log(String(console.log('Not undefined')) === 'undefined'); console.log(String(console.log('Not undefined')) !== 'Not undefined');

console.log(String(console.log('Not undefined')) === 'undefined');
console.log(String(console.log('Not undefined')) !== 'Not undefined');

我觉得这两行代码应该给我错误的信息,但是?如果有人可以向我解释?

让我们将其划分为多个级别,以使此行为更清晰。 首先在第一行中执行最里面的命令:

console.log('Not undefined')

在这里, console.log函数回显"Not undefined"但返回undefined 这是JavaScript 中所有函数默认行为 如果它们未显式返回某些内容,则它们将返回undefined值。 从那里开始,我们一步一步地将undefined强制转换为带有此行的string

String(console.log('Not undefined'))

如果我们结合先前的见解,JavaScript运行时将出现以下情况:

String(undefined)

这是对字符串"undefined"求值。 接下来,您要进行字面比较( === 比较值和类型 ),其结果为true

第二行是一样的,只是你现在是比较String(console.log('Not undefined'))是不是'Not undefined'它是不是让您得到true为好。

事实上,确实如此。 如果在开发人员工具中运行代码,则会注意到它返回三个输出:未定义,“未定义”和“未定义”。 实际的未定义结果(不是字符串,它实际上是未定义的)来自console.log命令本身-虽然console.log能够将输出分别打印到控制台,但它本身会返回未定义的结果。 “未定义”字符串来自String函数,该函数似乎具有其自己的输出(不确定原因)。 然后,您将获得所需的结果-“未定义”。 因此,实际上,它确实将所需的字符串输出到控制台,但是当您尝试将代码分配给变量时,如下所示:

var myVar = console.log(String(console.log('Not undefined')));

myVar返回未定义。 但是,它仍然将输出打印到控制台。

console.log(String(console.log('Not undefined')) === 'undefined');

对于第一个,您可以从最深层次的调用中获得: console.log('Not undefined') ,它显然输出Not undefined 然后将结果(不是控制台中实际的给定字符串)提供给String()函数,该函数返回undefined的字符串版本,即'undefined' 总而言之,与'undefined'相比,它返回true

对于另一个,它几乎是相同的:

console.log(String(console.log('Not undefined')) !== 'Not undefined');

在这里console.log('Not undefined')只是将字符串记录到控制台, 但是将 undefined赋予String(),它将String转换为"undefined" 然后与"Not undefined"相比,两者都是字符串,但是它们是不同的。 返回true

暂无
暂无

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

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