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

JS字符串反转函数返回含undefined结果,变量已声明仍异常

问题原因及解决方案

原因分析

数组索引从0开始计数,你的循环初始值用了splitString.length,这个值超出了数组的有效索引范围。比如输入"word"时,拆分后的数组长度是4,有效索引是0、1、2、3,当i=4时,splitString[4]会返回undefined,这个undefined被拼接到了结果字符串的开头,最终就出现了undefineddrow的错误输出。

修复后的代码

// reverse the word
function wordReverse (input) {

    // create variable to store new value
    let newString = "";
    // split string into array of seperate letters
    let splitString = input.split('');
    // 从最后一个有效索引开始循环(length - 1)
    for (let i = splitString.length - 1; i >= 0; i--) {

        newString += splitString[i];

    }

    return newString;

}

const test = wordReverse("word");
console.log(test); // 输出: drow

更简洁的实现方式(可选)

JavaScript数组自带反转方法,不用手动写循环就能实现需求:

function wordReverse(input) {
    return input.split('').reverse().join('');
}

const test = wordReverse("word");
console.log(test); // 输出: drow

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 04:30:57