首页 > 解决方案 > !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("");

}

那么它们之间有什么区别呢?

标签: javascriptcoercion

解决方案


由于运算符优先级(!具有更大的优先级==),!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"


推荐阅读