JavaScript Math.imul() 方法



JavaScript 的 Math.imul() 方法接受两个参数,并返回将它们相乘的结果作为 32 位有符号整数。此方法通常用于按位运算或某些需要使用 32 位整数的场景。

语法

以下是 JavaScript Math.imul() 方法的语法:

Math.imul(a, b)

参数

此方法接受两个参数。具体描述如下:

  • a: 要相乘的第一个整数。
  • b: 要相乘的第二个整数。

返回值

此方法返回一个数值,表示对提供的参数进行 C 风格的 32 位乘法的结果。

示例 1

在下面的示例中,我们使用 JavaScript Math.imul() 方法将数字 5 和 6 相乘:

<html>
<body>
<script>
   const result = Math.imul(5, 6);
   document.write(result);
</script>
</body>
</html>

输出

执行上述程序后,返回的结果为 30。

示例 2

这里,我们使用 Math.imul() 方法处理负数。

<html>
<body>
<script>
   const result = Math.imul(-5, 4);
   document.write(result);
</script>
</body>
</html>

输出

它返回 -5 乘以 4 的结果的低 32 位。

示例 3

在这个例子中,我们使用 Math.imul() 方法执行两个二进制数 (1010 和 1101) 的按位乘法:

<html>
<body>
<script>
   const a = 0b1010; //10
   const b = 0b1101; //13
   const result = Math.imul(a, b);
   document.write(result);
</script>
</body>
</html>

输出

如果我们执行上述程序,结果将是 40。

广告
© . All rights reserved.