Skip to content

[js] 第92天 解释下为什么{} + [] === 0为true? #904

Open
@haizhilin2013

Description

@haizhilin2013

第92天 解释下为什么{} + [] === 0为true?

Activity

ghost

ghost commented on Jul 16, 2019

@ghost

那个 {} 是空语句块而非空对象

{} + [] === 0
+[] === 0
0 === 0
true
NicholasBaiYa

NicholasBaiYa commented on Jul 17, 2019

@NicholasBaiYa

先运算,后比较
{} + [] == 0; 0 === 0

nowherebutup

nowherebutup commented on Jul 17, 2019

@nowherebutup

因为 +[] 为0,
而{}是空的,
所以 0 === 0;

changed the title [-][js] 第92天 解释下为什么`{} + [] === 0`为true?[/-] [+][js] 第92天 解释下为什么{} + [] === 0为true?[/+] on Jul 17, 2019
tonyChenHey

tonyChenHey commented on Jul 17, 2019

@tonyChenHey

加法运算符会触发三种类型转换:

  • 转换为原始值
  • 转换为数字
  • 转换为字符串

所以,这应该涉及到了隐式转换
那么是如何转换的呢?
这个过程涉及到将对象转换为原始值(undefined,null,boolean,number,string)
参考
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Symbol/toPrimitive
尝试干扰转换原始值的过程验证
console.log({[Symbol.toPrimitive](hint) {return "object";}} + []) //object

一开始以为{}不是代码块,但是这么多人说是代码块,为什么,求解

MoveZZG

MoveZZG commented on Jul 17, 2019

@MoveZZG

{} 认定是语法块
这个放在前面,只有混淆作用,并不参与运算。
+[] 类型转换 0
0===0;
不再赘述

DarthVaderrr

DarthVaderrr commented on Jul 17, 2019

@DarthVaderrr

{ }被解释为代码块,不参与计算 所以 +[ ] === 0;
但是如果写成 [ ] + { } 则结果为 "[object Object]"
详细介绍:
https://www.cnblogs.com/MasterYao/p/7783004.html

134355

134355 commented on Jul 17, 2019

@134355

{} + {} => '[object Object][object Object]'
{} + [] => 0
如果{}被当做代码块解析了,那么结果应该如下
+{} => '[object Object]'
+[] => 0
语句一与结果不符
语句二倒是能解析的通
现在我就看你们怎么解释

liangchaofei

liangchaofei commented on Jul 18, 2019

@liangchaofei

image
是false

134355

134355 commented on Jul 19, 2019

@134355

image
是false

image

zhangsan08

zhangsan08 commented on Jul 19, 2019

@zhangsan08

image
• 假

因为console.log的()把{}解析成一个对象了

MRMrmRmrrighty

MRMrmRmrrighty commented on Oct 23, 2020

@MRMrmRmrrighty

let a = {} + []
a === 0
false

maxthonl

maxthonl commented on Oct 30, 2020

@maxthonl

image

这个不用我多说,大家应该都清楚啥意思了吧

1684838553

1684838553 commented on Dec 9, 2021

@1684838553

{} + [] === 0
{} 在这表示代码块
+[] ==> +"" ==> 0

xiaoqiangz

xiaoqiangz commented on Jun 23, 2022

@xiaoqiangz

那个 {} 是空语句块而非空对象

{} + [] === 0
+[] === 0
0 === 0
true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    jsJavaScript

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @haizhilin2013@xiaoqiangz@MoveZZG@tonyChenHey@maxthonl

        Issue actions

          [js] 第92天 解释下为什么{} + [] === 0为true? · Issue #904 · haizlin/fe-interview