【问题标题】:comma in console.log (JavaScript)console.log 中的逗号 (JavaScript)
【发布时间】:2016-11-09 03:38:24
【问题描述】:

这可能是一个愚蠢的问题,但我不明白。我真的希望我不会投反对票

当我尝试运行这段代码时

var mydate= new Date (19995,10,5);
console.log("foo was born on the day :" mydate.getDay());

在 firebug (Mozeilla) 中,我得到一个错误(SyntaxError: missing) 在参数列表之后),但是当我在字符串和变量之间添加逗号时:

var mydate= new Date (19995,10,5);
console.log("foo was born on the day :", mydate.getDay()); 

它有效。为什么要加逗号?

【问题讨论】:

  • 由于印刷错误而投票关闭此主题为题外话的人是错误的,这是一个“语法”问题,尽管相似但它们非常不同。好问题 +1
  • 我在这里并没有真正得到那么多。谢谢@AdamBuchananSmith

标签: javascript string var console.log


【解决方案1】:

您需要使用 + 运算符而不是逗号,如下例所示。

console.log("foo was born on the day: " + maydate.getDay());

这也适用于变量/等。就像下面的例子一样。您还可以在变量后添加另一个 + 运算符以继续文本。

console.log("foo is " + fooAge + " years old");

【讨论】:

    【解决方案2】:

    我们在传递参数时使用逗号,console.log 获取这些参数,将它们合并在一起并打印输出。

    【讨论】:

    • 所以这只是对 console.log 的限制?
    • developer.mozilla.org/en/docs/Web/API/Console/log 是的,因为它是一个函数(一种方法,更深层次的含义),你传递参数,所以你用逗号分隔它们。如果你想做string concat (join, put together),你需要使用'+'。示例:var name = 'John'; var str = "Hi, my name is " + name;
    • 所以就好像我正在将参数传递给像 function my Function( X , Y) { //foo Code } 这样的函数
    • 是的,其中 X 和 Y 可以是字符串或变量
    【解决方案3】:

    使用“+”连接:

    console.log("foo was born on the day :" + maydate.getDay());
    

    【讨论】:

      猜你喜欢
      • 2019-01-21
      • 1970-01-01
      • 2017-03-29
      • 1970-01-01
      • 1970-01-01
      • 2020-10-26
      • 2012-05-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多