当前位置: 动力学知识库 > 问答 > 编程问答 >

comparison - Compare types in Javascript

问题描述:

I saw in Crockford's Book Javascript: The Good Parts that he does typeof comparison like this:

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

I made my own tests and I think this is the "ordering" of the different types:

function < number < object or array < string < undefined

Is this how JS actually does the comparison?

网友答案:

The typeof operator returns a string. String are compared by its numeric value.

So, the < comparison order would be:

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 are the first characters of the types. The charCodeAt method returns the numeric charCode of a character in JavaScript.

I have added an example of each type at the previous block. Most JavaScript developers know about the first types. The final type, xml, is less commonly known, and can be obtained by using typeof on EX4.

Demo of typeof: http://jsfiddle.net/9G9zt/1/

网友答案:

It is not importance. typeof returns a string, and the comparison operators work for strings, by performing a "a simple lexicographic ordering on sequences of code point value values".

Basically, if one string starts with the other, then that is the greater of the two, otherwise the first character position that differs between the two is compared.

See section 11.8.5 of the spec

分享给朋友:
您可能感兴趣的文章:
随机阅读: