[英]Can someone explain why i'm getting 9 & 5 instead of 36880 & 375
For my return, I'm getting 9 and 5 instead of 362880 and 375. Can someone explain what I missed?对于我的回报,我得到 9 和 5 而不是 362880 和 375。有人可以解释我错过了什么吗?
function multiplyAll(num){ // declare a function name multyplyAll with a num parameter for (let i = 0; i < num.length; i++){ // for loop to iterate base on the length of the parameter. num *= num[i] // multiplies them all together. } return num // function outpout } console.log(multiplyAll(9, 4, 5, 6, 7, 2, 1, 8, 3)) // should log: 362880 console.log(multiplyAll(5, 5, 5, 3)) // should log: 375
When you are using num
without rest parameters
then only the first value will get assign to num
.当您使用没有
rest parameters
的num
时,只有第一个值将分配给num
。 You are treating like num
is an array but num
is just of type number您将
num
一个数组,但num
只是 number 类型
There is no length
property on num
, Because num
is of type number. num
上没有length
属性,因为num
是 number 类型。 It won't run the for
loop and return the first element ie 9
and 5
它不会运行
for
循环并返回第一个元素,即9
和5
You should use collect then in to an array using rest parameters
您应该使用 collect 然后使用
rest parameters
进入数组
function multiplyAll(...num) { // declare a function name multyplyAll with a num parameter let res = 1; for (let i = 0; i < num.length; i++) { // for loop to iterate base on the length of the parameter. res *= num[i]; // multiplies them all together. } return res; // function outpout } console.log(multiplyAll(9, 4, 5, 6, 7, 2, 1, 8, 3)); // should log: 362880 console.log(multiplyAll(5, 5, 5, 3)); // should log: 375
You can also use reduce
here as:您也可以在此处使用
reduce
作为:
function multiplyAll(...num) { return num.reduce((acc, curr) => acc * curr, 1); } console.log(multiplyAll(9, 4, 5, 6, 7, 2, 1, 8, 3)); // should log: 362880 console.log(multiplyAll(5, 5, 5, 3)); // should log: 375
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.