You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript函数中的for循环无法执行是什么原因?

问题原因

你的for循环判断条件写反了。
当前你写的循环条件是i > inputArray.length - 1,初始i值为0,当你传入长度为3的数组时,inputArray.length - 1的计算结果是2,0 > 2的布尔值为false,循环条件从第一次判断就不成立,因此循环体完全不会执行,函数直接返回初始值0。

修复方案

你需要遍历所有相邻的元素对,i的取值范围应该是从0到inputArray.length - 2,对应的循环条件改为i < inputArray.length - 1即可。

修复后的代码如下:

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') // 正常执行
        if(inputArray[i] <= inputArray[i + 1]){
            total += inputArray[i + 1] - inputArray[i] + 1
        }
    }
    return total
}

console.log(arrayChange([1, 3, 4])); // 输出 5

内容的提问来源于stack exchange,提问作者user8672583

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 01:06:02