JavaScript 测验#7
💡一则或许对你有用的小广告
欢迎加入小哈的星球 ,你将获得:专属的项目实战 / 1v1 提问 / Java 学习路线 / 学习打卡 / 每月赠书 / 社群讨论
- 新项目:《从零手撸:仿小红书(微服务架构)》 正在持续爆肝中,基于
Spring Cloud Alibaba + Spring Boot 3.x + JDK 17...
,点击查看项目介绍 ;- 《从零手撸:前后端分离博客项目(全栈开发)》 2 期已完结,演示链接: http://116.62.199.48/ ;
截止目前, 星球 内专栏累计输出 82w+ 字,讲解图 3441+ 张,还在持续爆肝中.. 后续还会上新更多项目,目标是将 Java 领域典型的项目都整一波,如秒杀系统, 在线商城, IM 即时通讯,权限管理,Spring Cloud Alibaba 微服务等等,已有 2800+ 小伙伴加入学习 ,欢迎点击围观
今天我们正在研究 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>