[英]Javascript - How to return the correct value with the multiplication of all the elements of an array?
What I'm trying to do here it's multiply all the elements of the array A. With these values: [1,2,0,-5]it should returns 0... but it returns 1. What I'm doing wrong? 我在这里尝试执行的操作是将数组A的所有元素相乘。使用以下值:[1,2,0,-5]它应该返回0 ...但是它返回1。我在做什么错? Here's the code: 这是代码:
function solution(A){
let multi = 1;
for(i = 1; i < A.length; i++){
multi *= A[i]
}
if(multi = 30){
return 1
} else if (multi = -30){
return -1
} else if (multi = 0){
return 0
} else{
console.log("hey hey");
}
}
solution(A = [1,2,0,-5])
Your loop is starting at 1
- JavaScript arrays (and arrays in many other languages) are 0-indexed, so start at 0
. 循环从1
开始-JavaScript数组(以及许多其他语言的数组)的索引为0,因此从0
开始。 Your if
conditions are also wrong - use the comparison operator ==
not the assignment operator =
. if
条件也不对,请使用比较运算符==
而不是赋值运算符=
。
function solution(A){
let multi = 1;
for(i = 0; i < A.length; i++){
multi *= A[i]
}
if(multi == 30){
return 1
} else if (multi == -30){
return -1
} else if (multi == 0){
return 0
} else{
console.log("hey hey");
}
}
Javascript arrays start at 0 not 1. Anyway since that is causing trouble you should use the "reduce" function to multiple the elements of an array as this avoids the need worrying about the indices. Javascript数组从0而不是1开始。无论如何,这会导致麻烦,因此您应该使用“ reduce”函数对数组的多个元素进行操作,因为这样可以避免担心索引。
let mult = A.reduce((a,b)=>a*b);
With the if there is an assignment not a comparison. 如果有分配,则没有比较。 if(multi=30) then tests whether multi is non-zero, which it is because it is 30. One way to avoid this problem is putting the constant on the left:- if(multi = 30)然后测试multi是否为非零,这是因为它为30。一种避免此问题的方法是将常数放在左侧:
if(30 === multi){
return 1
} else if (-30 ===multi){
return -1
} else if (0===multi){
return 0
} else{
console.log("hey hey");
}
Also passing values to functions is by position. 还将值传递给函数是按位置。 No need to name the parameter, it is incorrect to do that. 无需命名参数,这样做是不正确的。
solution([1,2,0,-5]);
function solution(A){ const mult = A.reduce((a, b) => a*b); return mult == 30 ? 1 : mult == -30 ? -1 : 0; } console.log(solution(A = [1,2,0,-5]));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.