javascript - !typeof str == "string" 和 typeof str != "string" 的区别
问题描述
我正在编写一个简单的 if 条件来检查输入的类型。我用!typeof str == "string"
它不起作用,所以我用typeof str != "string"
它代替它。有效。这是功能:
function reverseStr(str) {
if (typeof str != "string" || !str) {
return "Please enter a valid str";
}
var oldList = str.split("");
var newList = [];
for (let i = oldList.length - 1; i >= 0; i--) {
newList.push(oldList[i]);
}
return newList.join("");
}
那么它们之间有什么区别呢?
解决方案
由于运算符优先级(!
具有更大的优先级==
),!typeof str == "string"
等价于(!typeof str) == "string"
,这意味着the boolean value opposite to the type of str is equal to "string"
并且将始终为假,因为!typeof str
返回false
,并且false != "string"
。
typeof str != "string"
有效,因为它意味着the type of str is not equal to "string"
。
推荐阅读
- javascript - 如何使用 javascript 动态复制或添加更多 html 表单字段?
- google-cloud-platform - 如何将日志从 GCP 的 Logs Viewer 传输到 Slack 或电子邮件?
- python - 是否可以将变量分配为字典中的值(对于 Python)?
- node.js - 将 n8n 部署到 Heroku
- sql - 如何使用 TSQL 引用表 SCHEMA?
- excel - 带条件的 PowerPivot 过滤器
- excel - 无重复数据
- java - Java - 接口 - 如何在多个活动中一起分配特定接口
- python - Python DataFrame:拆分为列表
- php - .htaccess 更改后 Yii2 找不到 /backend/web