JS代码运行时document.write变量显示错位问题求修正
问题根因
错误出在nextAge = currentAge++;这行代码的后缀自增逻辑:
- 后缀自增
变量++的执行逻辑是先返回变量的原始值,再对变量本身做加1操作 - 这行代码执行后,
nextAge拿到的是currentAge加1前的旧值,而currentAge本身反而变成了加1后的新值,所以两个数值输出时位置刚好颠倒。
修正后的代码
let yourName = prompt('What is your name?'); // 把prompt返回的字符串转成数字,避免后续计算出现字符串拼接错误 let currentAge = Number(prompt('How old are you?')); let nextAge if(currentAge){ // 直接做加1计算,不修改currentAge本身的原始值 nextAge = currentAge + 1; document.write(`Hi ${yourName}, You are ${currentAge} years old and next year you will be ${nextAge} years old`); };
改动说明
- 给
prompt获取的年龄加了Number()转数字处理,避免输入数字后出现20 + 1 = "201"的字符串拼接错误 - 把后缀自增改为直接
currentAge + 1赋值给nextAge,不会修改currentAge的原始值,输出位置就和预期一致 - 如需中文提示词,直接修改
prompt和document.write里的文本内容即可,核心逻辑不需要调整
内容的提问来源于stack exchange,提问作者JesusMedina
相关产品推荐
相关产品推荐

