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

JavaScript使用for循环拼接字符串时开头出现undefined?原因排查

字符串反转函数开头出现undefined的原因及解决方法

你的问题根源在循环的初始索引设置上:

  • JavaScript字符串的索引从0开始,长度为n的字符串,最后一个有效字符的索引是n-1
  • 当索引等于字符串长度(即string.length)时,访问string[i]会返回undefined

看你的代码,循环初始值设为i = string.length,第一次循环就会把undefined拼接到newWord开头,这就是输出带undefined的原因。另外,循环变量i没有用let声明,会变成全局变量,建议补上避免全局污染。

修正后的代码如下:

const reverseString = function(string) {
    let newWord = "";
    for (let i = string.length - 1; i >= 0; i--) {
        newWord = newWord.concat(string[i]);
    }
    return newWord
};

如果用+=运算符,写法类似:

const reverseString = function(string) {
    let newWord = "";
    for (let i = string.length - 1; i >= 0; i--) {
        newWord += string[i];
    }
    return newWord
};

调用reverseString("Hello")就会得到预期的olleH。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 12:23:20