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

如何在HTML文本框中输出逗号分隔的降序奇数

问题原因

循环内每次执行result.value = ${i}``都会直接覆盖输入框的原有内容,没有保留之前生成的数字,所以运行结束后只会显示最后一次循环的数字1。

修正方案

推荐先收集所有符合要求的奇数到数组中,再用逗号拼接为完整字符串后一次性赋值给输入框,既避免了循环内重复查询DOM的性能损耗,也不会出现末尾多余逗号的问题。

修正后的完整代码

HTML代码

<form id = "numbersdescendingodd">
       Resultdescendingodd : <input type = "text" name = "resultdescendingodd" id = "dodd" max = "20"><br>
       <input type = "button" onclick = "descendingodd()" value = "Clickhere">
       <br>
  </form>

JavaScript代码

function descendingodd(){
    // 提前获取DOM元素,避免循环内重复查询
    const resultInput = document.getElementById('dodd');
    // 收集所有符合要求的奇数
    const oddList = [];
    for(let i = 21 ; i>=1; i-=2){
        oddList.push(i);
    }
    // 用逗号拼接后赋值给输入框
    resultInput.value = oddList.join(',');
 }

如果你想基于原有写法最小改动,也可以用字符串拼接后处理末尾逗号的方式实现:

function descendingodd(){
    var result = document.getElementById('dodd');
    result.value = ''; // 先清空原有内容
    for(var i = 21 ; i>=1; i-=2){
        result.value += `${i},`
     }
    // 去掉最后多余的逗号
    result.value = result.value.slice(0, -1);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 09:15:04