首页 > 解决方案 > 为什么这个 for 循环不在打字稿函数中执行?

问题描述

我不明白为什么这个函数中的 for 循环永远不会运行。我在每个控制台日志旁边写了返回的内容。谁能帮我弄清楚为什么?

export function arrayChange(inputArray: number[]): number {
    let total = 0;
    console.log('inputArray.length', inputArray.length) // returns 3
    console.log('inputArr', inputArray[0] <= inputArray[1]) //returns true
    for(let i = 0; i > inputArray.length - 1; i++){
        console.log('hello') //never runs
        if(inputArray[i] <= inputArray[i + 1]){
            total += inputArray[i + 1] - inputArray[i] + 1
        }
    }
    return total
}

console.log(arrayChange([1, 3, 4])); //returns 0


标签: typescript

解决方案


你有你的条件倒退:

for(let i = 0; i > inputArray.length - 1; i++){
}

你的数组长度为 3,所以你开始的是:

for(let i = 0; i > 3 - 1; i++)

i因此永远不会大于 2。因此循环不会进行单次迭代。

你可能是这个意思(注意小于,而不是大于):

for(let i = 0; i < inputArray.length - 1; i++){
}

你现在从这个开始:

for(let i = 0; i < 3 - 1; i++)   // 0 < 2 - first loop iteration
for(let i = 0; i < 3 - 1; i++)   // 1 < 2 - second loop iteration
for(let i = 0; i < 3 - 1; i++)   // 2 < 2 - no more iteration!

假设您要实际迭代所有数组元素而不跳过最后一个,我们还没有完成。

这意味着条件仍然错误(使用<=或保留- 1):

for(let i = 0; i < inputArray.length; i++){
}

for(let i = 0; i < 3; i++)   // 0 < 3 - first loop iteration
for(let i = 0; i < 3; i++)   // 1 < 3 - second loop iteration
for(let i = 0; i < 3; i++)   // 2 < 3 - third loop iteration

因此,您已经迭代了所有 (3) 个数组元素。


推荐阅读