Javascript 模运算符的行为与其他语言不同 [英] Javascript modulo operator behaves differently from other languages

查看:50
本文介绍了Javascript 模运算符的行为与其他语言不同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据维基百科, 上的 模运算符(整数除法的余数)n 应该产生 0n-1 之间的结果.

According to Wikipedia, the modulo operator (remainder of integer division) on n should yield a result between 0 and n-1.

python中确实如此:

print(-1%5) # outputs 4

Ruby 中:

puts -1%5 # outputs 4

Haskell

main = putStrLn $ show $ mod (-1) 5

但是在Javascript中:

console.log(-1%5);

结果是-1 !!

The result is -1 !!

这是为什么?这个设计决定背后有什么逻辑吗?

Why is that ? is there logic behind this design decision ?

虽然 -1 等价于 45,但负值使其更难用作索引.

While -1 is equivalent to 4 modulo 5, negative values makes it harder to use as indices.

例如:

arr[x%5]

当数组长度大于 5 时,

pythonRuby 中总是有效的表达式,但在 Javascript 中,这是一个等待发生的异常.

would always be a valid expression in python and Ruby when the array length is more than 5, but in the Javascript, this is an exception waiting to happen.

推荐答案

如果您通过模数"理解欧几里得除法的其余部分在数学中很常见,% 运算符 不是模运算符.它被称为余数运算符,其结果始终与被除数具有相同的符号.(在 Haskell 中,rem 函数 这样做).

If by "modulus" you understand the remainder of the Euclidean division as common in mathematics, the % operator is not the modulo operator. It rather is called the remainder operator, whose result always has the same sign as the dividend. (In Haskell, the rem function does this).

这种行为在编程语言中很常见,尤其是在 C 和 Java 中,JavaScript 的算术约定的灵感来自于这些语言.

This behaviour is pretty common amongst programming languages, notably also in C and Java from which the arithmetic conventions of JavaScript were inspired.

这篇关于Javascript 模运算符的行为与其他语言不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆