为什么不添加 '+ ”“”在javascript中进行数学运算后,新变量长度的计数未定义?
我正在计算小时数,如果超过 12 小时,则将其减去 12(这样下午 1 点就不会显示为下午 13 点)。下面是我的 JavaScript 代码的一部分。
else if (hours[0] >= 13) {
hours[0] = hours[0] - 12 + "";
}
稍后在代码中,当我尝试计算数组变量“hours[0]”的长度时,如果我有此代码,则显示为未知:
else if (hours[0] >= 13) {
hours[0] = hours[0] - 12;
}
并且我不明白为什么。有人可以帮我吗?
I'm counting the number of hours and then subtracting it by 12 if it goes above 12 (so that 1pm doesn't appear as 13pm). Below is part of my javascript code.
else if (hours[0] >= 13) {
hours[0] = hours[0] - 12 + "";
}
Later in the code, when I'm trying count the length of the array variable 'hours[0]', it appears as unknown if I have this code instead:
else if (hours[0] >= 13) {
hours[0] = hours[0] - 12;
}
and I don't understand why. Could someone help me out please?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
无论
hours[0]
包含数字还是包含数字的字符串,减法hours[0] - 12
都会返回一个数字,例如"13"
。添加+ ""
将减法结果转换为字符串。 javascript 中的数字没有长度,因此调用数字的 length 成员将返回 undefined。The subtraction
hours[0] - 12
returns a number, no matter ifhours[0]
contains a number or a string containing a number, e.g."13"
. Adding the+ ""
converts the result of the subtraction to a string. A number has no length in javascript, and therefore invoking the length member of a number will return undefined.如果将
""
添加到表达式,则会将结果转换为字符串,并且字符串具有.length
属性。相反,数字没有.length
所以您遇到的情况是正常的......If you add
""
to an expression you're converting the resulto to a string and strings have a.length
property. Numbers instead do not have a.length
so what you're experiencing is normal...