!typeof str == "string" 和 typeof str != "string" 之间的区别

Difference between !typeof str == "string" and 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 returns falsefalse != "string".

typeof str != "string" 有效,因为它意味着 the type of str is not equal to "string".