JavaScript 循环中断并继续(JetBrains 练习)

JavaScript Loops Break and continue (JetBrains exercise)

You are given an array of numbers called numbers. Calculate the sum of numbers and return it from the function. If the next number is equal to 0, the program must stop processing the numbers and return the result.

Sample Input 1:**

11 12 15 10 0 100

Sample Output 1:

48

Sample Input 2:

100 0 100

Sample Output 2:

100

我无法让它工作,这就是我到目前为止所做的...

我是否应该创建一个每次进入循环时都会求和的计数器(以检查它是否为 0)和另一个获取 'n' 值并将其求和的计数器?

function sum(numbers) {
    let add = 0;

    for (let n in numbers) {
        if (numbers[n] === 0) {
            break;
        }
        if (numbers[n] !== 0) {
            add = numbers[n] + n;
            n++;
        }
        return (numbers[n]);
    }
}

for/in loops are for iterating over objects. 具有计数器的传统 for 循环或 Array.forEach() 用于数组。 (感谢@T.J.Crowder 的link) 此外,您只需要一个测试 0 并在出现这种情况时中断的语句,而不是两个单独的 if 语句。如果不是,则代码将继续 - - 如果需要则无需额外。最后, return 不应该在循环中。它应该在循环结束后发生。

function sum(numbers) {
    let add = 0;

    // Array.reduce() is really the best solution here, 
    // but not what your assignment wants you to use.
    // for/in is really for iterating over objects, 
    // while a counting `for` loop is for arrays
    for (var i = 0; i < numbers.length; i++) {
        if (numbers[i] === 0) {
            break;
        }
        
        // No need for another "if". If the code has
        // reached this point, the current array number
        // must not be zero, so just add it to the 
        // overall accumulator variable
        add += numbers[i];
    }
    
    return add;  // After iterating the loop, return the accumulator
}

console.log(sum([11, 12, 15, 10, 0, 100]));
console.log(sum([100, 0, 100]));

我发现您当前的代码存在多个问题。 首先,您应该以更好的方式命名该函数,以描述它的实际作用。你的 for 循环没有意义,因为 n in numbers 你得到的是元素而不是索引,所以 numbers[n] 没有意义。循环指令中的 let 不应该存在。 第二个 if 块可能是一个 else。 add应该设置为add + n,n++没有意义。 return 应该在循环之外,实际上 return 添加。

看来您对一般程序流程的了解不多,所以我建议您再看一下单条指令。如果您知道它们的含义,请尝试逐步在纸上执行您的算法,以了解它实际做什么与应该做什么。如果您难以理解当前的程序流程,您还可以添加一些 console.log(...)。

这次又解决了一个问题,多亏了解释,类似上面那个,希望能帮到大家:

在给定数组中找到数字 5 的第一个出现位置及其索引 return。如果找不到号码,return-1.

示例输入 1:

10 3 8 5 3 4 5

示例输出 1:

3

示例输入 2:

5 10 111 12

示例输出 2:

0

 function find5(numbers) {
    let find = 5;
    for (let v = 0; v < numbers.length; v++) {
        if (numbers[v] !== find) {
            continue;
        }
        return (v);
    }
    return(-1);
}

console.log(find5([10, 3, 8, 5, 3, 4, 5]));
console.log(find5([3, 4, 1]));