javascript - 比较 Javascript 中的类型

标签 javascript comparison typeof

我在 Crockford 的书 Javascript: The Good Parts 中看到他是这样进行类型比较的:

return typeof a < typeof b ? -1 : 1;

我做了自己的测试,我认为这是不同类型的“排序”:

function < number < object or array < string < undefined

这就是 JS 实际进行比较的方式吗?

最佳答案

typeof运算符返回一个字符串。字符串按其数值进行比较。

因此,<比较顺序为:

type       charCode ("tfnosux".charCodeAt(i))   Example
boolean     98                                   true
function   102                                   Date
number     110                                   123
object     111                                   []
string     115                                   ""
undefined  117                                   undefined
xml        120                                   <x></x>

tfnosux是类型的第一个字符 charCodeAt 方法返回 JavaScript 中字符的数字 charCode。

我在前面的 block 中添加了每种类型的示例。大多数 JavaScript 开发人员都知道第一种类型。最终类型,xml , 鲜为人知,可以通过使用 typeof 获得在 EX4 .

演示 typeof : http://jsfiddle.net/9G9zt/1/

关于javascript - 比较 Javascript 中的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8619026/

相关文章:

javascript - 引用错误 : exports is not defined in ES module scope

java - PriorityQueue 的比较如何工作

javascript - jQuery/Javascript 比较运算符 "==="和 "=="

javascript - 性能:typeof vs instanceof

JavaScript短路评估错误?

javascript - 如果 UUID 与字符串(autoIncrement)匹配,我如何移动到数组中的下一个项目?

javascript - 设置通知系统的最佳方法?

javascript - jQuery 自定义插件回调 - 新问题

ios - 更新到 Xcode 6.3 会破坏应用程序 - Google GTLTouchStaticLib "not equal to a null pointer is always true"

Swift —— 等同于 typealias 中的 typeof 的惯用语