JavaScript 测验#7

一则或许对你有用的小广告

欢迎加入小哈的星球 ,你将获得:专属的项目实战 / Java 学习路线 / 一对一提问 / 学习打卡/ 赠书活动

目前,正在 星球 内带小伙伴们做第一个项目:全栈前后端分离博客项目,采用技术栈 Spring Boot + Mybatis Plus + Vue 3.x + Vite 4手把手,前端 + 后端全栈开发,从 0 到 1 讲解每个功能点开发步骤,1v1 答疑,陪伴式直到项目上线,目前已更新了 204 小节,累计 32w+ 字,讲解图:1416 张,还在持续爆肝中,后续还会上新更多项目,目标是将 Java 领域典型的项目都整上,如秒杀系统、在线商城、IM 即时通讯、权限管理等等,已有 870+ 小伙伴加入,欢迎点击围观

今天我们正在研究 JavaScript 中的 typeof 运算符。让我们开始正事吧!假设我们有以下简短的 JavaScript 代码:


 <script>
    var str = new String("Hello");
var result = typeof(str instanceof String);
alert(result); //What is the output of the alert? 

result = typeof typeof(str instanceof String);
alert(result); //What is the output of the alert? 

result = typeof typeof typeof(str instanceof String);
alert(result); //What is the output of the alert? 

</script>

问题 :警报的输出是什么,为什么?

*把你的答案写在一张纸上,然后阅读答案。*

回答

结果将是一个 布尔值 然后是 字符串 然后是 字符串 。让我们了解为什么会得到这些结果。在第一个表达式(非常简单)中,我们有:


 <script>
    var str = new String("Hello");
var result = typeof(str instanceof String);
alert(result); //What is the output of the alert? 

result = typeof typeof(str instanceof String);
alert(result); //What is the output of the alert? 

result = typeof typeof typeof(str instanceof String);
alert(result); //What is the output of the alert? 

</script>

分以下两步执行:
1. str instanceof String 将返回 true
2. typeof (true) 将返回 "boolean"

在第二个表达式中:


 <script>
    var str = new String("Hello");
var result = typeof(str instanceof String);
alert(result); //What is the output of the alert? 

result = typeof typeof(str instanceof String);
alert(result); //What is the output of the alert? 

result = typeof typeof typeof(str instanceof String);
alert(result); //What is the output of the alert? 

</script>

这将产生一个 string ,原因如下:
1. str instanceof String 将返回 true
2. typeof (true) 将返回 "boolean" 您会注意到,typeof(true) 返回一个包含“boolean”作为值的字符串。重要的是要知道 JavaScript typeof 运算符总是返回一个字符串。
3. 最后,很明显 typeof ("boolean") 将返回 "string"

这是第三个表达式:


 <script>
    var str = new String("Hello");
var result = typeof(str instanceof String);
alert(result); //What is the output of the alert? 

result = typeof typeof(str instanceof String);
alert(result); //What is the output of the alert? 

result = typeof typeof typeof(str instanceof String);
alert(result); //What is the output of the alert? 

</script>

它类似于第二个表达式: result 将返回“string”,因为第三个表达式将按以下步骤执行:
1. str instanceof String 将返回 true
2. typeof (true) 将返回 "boolean"
3. typeof ("boolean") 将返回 "string"
3. 最后, typeof ("string") 将返回 "string"

所以现在你可以猜到结果是什么了:


 <script>
    var str = new String("Hello");
var result = typeof(str instanceof String);
alert(result); //What is the output of the alert? 

result = typeof typeof(str instanceof String);
alert(result); //What is the output of the alert? 

result = typeof typeof typeof(str instanceof String);
alert(result); //What is the output of the alert? 

</script>