Javascript - 如何 return 将数组的所有元素相乘得到正确的值?

Javascript - How to return the correct value with the multiplication of all the elements of an array?

我在这里要做的是将数组 A 的所有元素相乘。使用这些值:[1,2,0,-5]它应该 returns 0... 但是它returns 1.我做错了什么?这是代码:

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])

您的循环从 1 开始 - JavaScript 数组(以及许多其他语言中的数组)是 0 索引的,因此从 0 开始。您的 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 数组从 0 而不是 1 开始。 无论如何,因为这会造成麻烦,您应该使用 "reduce" 函数来对数组的元素进行倍增,因为这样可以避免担心索引。

let mult = A.reduce((a,b)=>a*b);

如果有赋值而不是比较。 if(multi=30) 然后测试 multi 是否为 non-zero,因为它是 30。 避免此问题的一种方法是将常量放在左侧:-

  if(30 === multi){
        return 1
    } else if (-30 ===multi){
        return -1
    } else if (0===multi){
        return 0
    } else{
        console.log("hey hey");
    }

同样将值传递给函数是按位置的。不需要命名参数,这样做是不正确的。

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]));