【问题标题】:Why does some console.log print out typeof 1 as number, but sometimes as "number" (quoted)?为什么某些 console.log 将 typeof 1 打印为数字,但有时打印为“数字”(引用)?
【发布时间】:2017-02-25 08:41:59
【问题描述】:

在当前的 Google Chrome v56.0 和 Safari v9.1 中是这样:

在调试器控制台中,如果我输入:

> console.log(1, typeof 1)
  1 "number"

> console.log("1", typeof 1)
  1 number

为什么第一个是"number" 而第二个是number? (也就是说,为什么引用了第一个而没有引用第二个?

【问题讨论】:

  • 我认为是一个特定的问题
  • 我与控制台的结果相同(正如我先写的那样)
  • 好的,我删除了该评论
  • 这是一个奇怪的语法高亮差异......如果它是一个字符串,日志的第一个参数将永远是黑色的,那么后面的所有字符串参数也将是黑色的。但是如果第一个参数是其他类型,那么所有后面的字符串参数都是红色的,带引号。例如log("1", 1, "1") 字符串为黑色,log(null, "1", "1") 字符串为红色,log("1", null, "1") 字符串为黑色。
  • 控制台的行为不是标准化的(即它依赖于实现)。你为什么关心这些差异? typeof 总是返回一个字符串,无论是在控制台中表示为"number" 还是number 都不是特别重要。

标签: javascript google-chrome safari typeof


【解决方案1】:

这不仅仅是 typeof,与 console.log(1, "1");console.log("1", "1"); 一样。

我认为将引号放在那里是因为当您打印两种不同的类型时,它会为您区分它们。

【讨论】:

    【解决方案2】:

    看起来它需要调用toString(在必要时)作为将下一部分显示为字符串的模式。

    没有引号

    console.log("1", typeof 1)
        1 number
    
    console.log("", typeof 1)
        1  number
    
    console.log("0", typeof 1)
        0 number
    

    带引号

    console.log(1, typeof 1)
        1 "number"
    
    console.log({}, typeof 1)
        1 Object {} "number"
    
    console.log(false, typeof 1)
        1 false "number"
    
    console.log(true, typeof 1)
        1 true "number"
    
    console.log([], typeof 1)
        1 [] "number"
    
    console.log(() => true, typeof 1)
        1 () => true "number"
    
    console.log(/./, typeof 1)
        1 /./ "number"
    

    【讨论】:

    • 它不是用来引用的
    【解决方案3】:

    如果我们看一下 MDN 上的 the console.log 页面,它会解释:

    obj1 ... objN
    要输出的 JavaScript 对象列表。每个对象的字符串表示按列出的顺序附加在一起并输出。

    所以在第一个示例中,它结合了一个整数 (1) 和一个字符串 (typeof 1)。因为有一个整数,所以它将这两个值组合起来,然后将它们转换为字符串。所以1 现在等于字符串; 1typeof 1 现在等于 typeof 1 的输出字符串,即 "number"
    因此,结果字符串为1 "number"

    在第二个例子中,1 已经是一个字符串,所以它既不转换为字符串,又简单地将它们连接起来,所以结果正如预期的那样; 1 number.

    【讨论】:

    • console 没有标准化。 MDN 是一个公共 wiki,虽然那里的建议很有帮助,但它不是确定性的,而且对于特定于实现的主题,对于某些浏览器可能不正确。
    猜你喜欢
    • 2020-05-09
    • 1970-01-01
    • 2021-04-03
    • 1970-01-01
    • 2013-06-14
    • 1970-01-01
    • 2018-05-29
    • 2014-06-02
    • 2021-09-22
    相关资源
    最近更新 更多