Why is {} < function(){}?

ぐ巨炮叔叔 提交于 2019-12-06 01:18:20

问题


While I was messing around with truth tables in JavaScript, I noticed that the following evaluates to true:

var a, b, c;
a = {};
b = function(){};
c = a < b;
console.log(c);

Why?

I've only tested this in Firefox, and I'm sure I could dig up the details in the ECMAScript 2.6.2 spec, but TBH I'm feeling lazy.


回答1:


JavaScript type coercion makes the comparison essentially

String({}) < String(function(){})

so essentially you are just doing

"[object Object]" < "function (){}"

which is a lexicographic string comparison.




回答2:


Javascript compares objects by calling valueOf() or toString().
Since neither operand has a valueOf() method, it will compare the toString()s.

({}).toString() is [object Object].
(function() { }).toString() is function() { }.

[ is less than f.




回答3:


alert(({}))            -> [object Object]
alert((function(){}))  -> function () {}

[ comes before f, hence ({}) < (function () {}).

Yes, it's silly. ;)




回答4:


pretty simple and easy ( internally they are both converted to strings ) this is because in Javascript

If an object is compared with a number or string, JavaScript attempts to return the default value for the object. Operators attempt to convert the object to a primitive value, a String or Number value, using the valueOf and toString methods of the objects.

so when both are compared both objects are converted to string using the internal Tostring method

    a.toString()
"[object Object]"

b.toString()
"function () { }"

hence b will be greater than a ( larger string ) that's why b > a is true



来源:https://stackoverflow.com/questions/8116407/why-is-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!