js中整除符号_在javascript中对字符串使用除法运算符(/)

I realized that in javascript all 101/100, "101"/100, 101/"100" and "101"/"100" result in 1.01 (checked on Chrome, FF and IE11). But I cannot find a piece of documentation regarding this behaviour.

Therefore my question is if it is (cross-browser) safe to use this feature, and if it is a good practice to do so (or rather to use parseInt before division if the variable can be a string)?

解决方案Therefore my question is if it is (cross-browser) safe to use this feature...

It depends on your definition of "safe." With the division operator, yes, it's specified behavior: Each operand is converted (implicitly coerced) to a number, and then numeric division is done.

But beware of generalizing this too far. You'll be okay with /, *, and - but it will bite you on +, because if either operand to + is a string, + does string concatenation, not addition.

Another way that it may or may not be "safe" depending on your point of view is the implicit coercion: It uses the browser's JavaScript engine's rules for converting strings to numbers. Some older browsers went beyond the specification (which they were allowed to in the past) and treated numbers starting with a 0 as octal (base 8) rather than decimal. Naturally, end users who type in, say, "0123" as a number probably mean the number 123, not the number 83 (123 in octal = 83 decimal). JavaScript engines are no longer allowed to do that, but some older ones do.

In general, it's probably best to explicitly coerce or convert those operands. Your choices for doing so:

The unary + operator: value = +value will coerce the string to a number using the JavaScript engine's standard rules for that. Any non-digits in the string (other than the e for scientific notation) make the result NaN. Also, +"" is 0, which may not be intuitive.

The Number function: value = Number(value). Does the same thing as +.

The parseInt function, usually with a radix (number base): value = parseInt(value, 10). The downside here is that parseInt converts any number it finds at the beginning of the string but ignores non-digits later in the string, so parseInt("100asdf", 10) is 100, not NaN. As the name implies, parseInt parses only a whole number.

The parseFloat function: value = parseFloat(value). Allows fractional values, and always works in decimal (never octal or hex). Does the same thing parseInt does with garbage at the end of the string, parseFloat("123.34alksdjf") is 123.34.

So, pick your tool to suit your use case. :-)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值