Why does {} == false evaluate to false while [] == false evaluates to true?(为什么 {} == false 评估为 false 而 [] == false 评估为 true?)
问题描述
为什么 {} == false 评估为 false 而 [] == false 评估为 true在 JavaScript 中?
Why does {} == false evaluate to false while [] == false evaluates to true in javascript?
推荐答案
这是根据抽象等式比较算法:
{} == false // step 7 {} == ToNumber(false)
{} == 0 // step 9 ToPrimitve({}) == 0
"[object Object]" == 0 // step 5 ToNumber("[object Object]") == 0
NaN == 0 // step 1.c.i
[] == false // step 7 [] == ToNumber(false)
[] == 0 // step 9 ToPrimitve([]) == 0
"" == 0 // step 5 ToNumber("") == 0
0 == 0 // step 1.c.iii
参考:ToNumber,ToPrimitive
因此,更喜欢使用严格比较.
And because of this, prefer to use strict comparison.
ToPrimitive 如何在比较过程中将对象转换为基元 的一些示例.默认情况下,将调用对象的 valueOf 方法,如果 valueOf 没有返回原始值,则调用 toString.对于 Date 对象,它会默认调用 toString.
Some examples how ToPrimitive converts objects to primitives during comparison. By default, the valueOf method of the object will be called, and then toString if valueOf doesn't return a primitive value. For Date objects it will call toString by default.
var obj = {};
obj.valueOf(); // Object { } // the object itself
obj.toString(); // "[object Object]"
obj.valueOf = function() { return 123; };
obj == 123; // true
obj.toString = function() { return 'foo bar'; };
obj == 123; // false
obj == 'foo bar'; // true
// Date object
var date = new Date();
date.valueOf(); // 1421430720379
date.toString(); // "Fri Jan 16 2015 09:52:00 GMT-0800 (PST)"
date == 1421430720379 // false
date == "Fri Jan 16 2015 09:52:00 GMT-0800 (PST)" // true
date.toString = function() { return 'foo'; };
date == 'foo'; // true
这篇关于为什么 {} == false 评估为 false 而 [] == false 评估为 true?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么 {} == false 评估为 false 而 [] == false 评估为 true?
基础教程推荐
- npm start 错误与 create-react-app 2022-01-01
- Bokeh Div文本对齐 2022-01-01
- 检查 HTML5 拖放文件类型 2022-01-01
- 如何添加到目前为止的天数? 2022-01-01
- Bootstrap 模态出现在背景下 2022-01-01
- 即使用户允许,Gmail 也会隐藏外部电子邮件图片 2022-01-01
- 原生拖动事件后如何获取 mouseup 事件? 2022-01-01
- 在 contenteditable 中精确拖放 2022-01-01
- fetch 是否支持原生多文件上传? 2022-01-01
- Fabric JS绘制具有活动形状的多边形 2022-01-01
