【问题标题】:Checking the equality of different kind of functions in Javascript检查Javascript中不同类型函数的相等性
【发布时间】:2016-01-03 12:34:56
【问题描述】:
function a(){ return true; }
var b = function(){ return true; };
window.c = function(){ return true; };


console.log(typeof a);//returns funtion
console.log(typeof b);  //returns funtion
console.log(typeof window.c);   //returns funtion

typeof a === typeof b === typeof window.c  //returns false

在控制台中运行上述代码时,最后的语句为 false。而所有 3 个函数的 typeof 都返回函数。我知道 javascript 中有一些带有 typeof 的奇怪部分..你们能解释一下吗..

【问题讨论】:

  • 答案: true === typeof window.cfalse
  • typeof a === typeof b 被评估为true

标签: javascript equality typeof


【解决方案1】:

问题与类型不相等无关,而是以下事实:

a === b === c

被解释为:

(a === b) === c

所以这意味着第一个测试typeof a === typeof b 被解析为true,现在您执行类似true === typeof window.c 的相等性检查。

你可以通过重写条件来解决问题:

(typeof a === typeof b) && (typeof b === typeof window.c)

【讨论】:

  • (a === b) ==== c,嗯? 4=。这对我来说是新的。
  • @Tushar:感谢您的发现。那确实是一个错字。非常感谢。
猜你喜欢
  • 2013-05-31
  • 1970-01-01
  • 2017-01-20
  • 2012-02-23
  • 1970-01-01
  • 2015-11-23
  • 2020-03-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多