我可以在 JavaScript 中不使用乘法运算符“*”来执行乘法吗

Sha*_*ool 0 javascript

我需要在 JavaScript 中将两个数字相乘,但我不需要使用乘法运算符“*”。是否可以?

function a(b,c){
    return b*c;
} // note:need to do this without the "*" operator
Run Code Online (Sandbox Code Playgroud)

Ami*_*oki 7

是的。因为乘法只是多次加法。也有有意义的方法签名,而不是使用单个字母。

function multiply(num, times){
   // TODO what if times is zero
   // TODO what if times is negative
   var n = num;
   for(var i = 1; i < times; i++)
      num += n; // increments itself
   return num;
} 
Run Code Online (Sandbox Code Playgroud)

  • 解释downvote 对我和我的代码都有好处,因为两者都得到了改进。 (2认同)