【问题标题】:plus signs in the JS code - why aren't they optional hereJS 代码中的加号 - 为什么它们在这里不是可选的
【发布时间】:2014-04-14 08:22:28
【问题描述】:

我很好奇 Dagg Nabbit 在 SO here: Convert HH:MM:SS string to seconds only in javascript

var seconds = (+a[0]) * 60 * 60 + (+a[1]) * 60 + (+a[2]); 

对,

var seconds = (a[0]) * 60 * 60 + (a[1]) * 60 + (a[2]); 

没有按预期工作 - 它不计算秒数。 为什么?

【问题讨论】:

  • 附注:并非所有加号运算符都是必需的:a[0] * 60 * 60 + a[1] * 60 + (+a[2]); 可以正常工作

标签: javascript string function time


【解决方案1】:

它们会导致将字符串隐式转换为数字。在浏览器的调试控制台中,尝试:

> typeof +'1'
"number"
> typeof '1'
"string"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-01
    • 1970-01-01
    • 2017-04-02
    • 1970-01-01
    • 1970-01-01
    • 2020-09-19
    相关资源
    最近更新 更多