需要在 Javascript 中使用 Switch Case 计算数组中零、正数和负数的个数

Need to calculate the number of zeros, positive and negative nos in an array using Switch Case in Javascript

我尝试了下面的代码,但是 switch case 没有像我预期的那样工作。你能告诉我哪里错了吗?

    function counter() {
 //   const arr = prompt("Enter numbers").split(",");
 let arr = [1,2,3,-1,0];
 console.log(arr.length);
    const neg=0, pos=0, zero=0;
    for (var i = 0; i < arr.length; i++) {
        let val = arr[i];
        console.log(val);
        switch (val) {
            case (val === 0):
                zero += 1;
                console.log("zero");
                break;  
            case (val < 0):
                neg += 1;
                console.log("neg");
                break;
            case (val > 0):
                pos += 1;
                console.log("pos");
                break;
            default:
                console.log("not working");
                break;
        }
    }
    document.write("Negatives: " + neg+"<br>");
    document.write("Positives: " + pos+"<br>");
    document.write("Zeroes: " + zero+"<br>");
}

您不能重新分配 const。这样的事情会引发错误:

const num = 0;
num += 1; // Uncaught TypeError: Assignment to constant variable.

另一个问题:在您的 case 语句中,您使用的表达式计算结果为 truefalse(表达式将在匹配之前计算),因此您将拥有使用 switch(true) 而不是 switch(val):

function counter() {
    // const arr = prompt("Enter numbers").split(",");
    let arr = [1,2,3,-1,0];
    let neg=0, pos=0, zero=0;
    for (var i = 0; i < arr.length; i++) {
        let val = arr[i];
        switch (true) {
            case (val === 0):
                zero += 1;
                console.log("zero");
                break;  
            case (val < 0):
                neg += 1;
                console.log("neg");
                break;
            case (val > 0):
                pos += 1;
                console.log("pos");
                break;
            default:
                console.log("not working");
                break;
        }
    }
    document.write("Negatives: " + neg+"<br>");
    document.write("Positives: " + pos+"<br>");
    document.write("Zeroes: " + zero+"<br>");
}

counter()