JavaScript初学者求助:风速发电量计算函数无法运行排查
修正后的风速发电量计算实现
完整HTML代码
<body> <input type="number" id="wind-strength" placeholder="Enter wind strength in m/s"> <button onclick="myFunction()"> Press </button> <p id="output-value"></p> </body>
完整JavaScript代码
function myFunction() { // 获取输入风速并转为数字类型 const windSpeed = parseFloat(document.getElementById("wind-strength").value); const outputElement = document.getElementById("output-value"); // 处理非数字输入 if (isNaN(windSpeed)) { outputElement.textContent = "请输入有效的风速数值"; return; } if (windSpeed >= 1.6 && windSpeed <= 3.3) { outputElement.textContent = "The wind turbine produces about 2 watts per hour"; } else if (windSpeed >= 3.4 && windSpeed <= 5.4) { outputElement.textContent = "The wind turbine produces about 10 watts per hour"; } else if (windSpeed >= 5.5 && windSpeed <= 7.9) { outputElement.textContent = "The wind turbine produces about 60 watts per hour"; } else if (windSpeed >= 8 && windSpeed <= 10.7) { outputElement.textContent = "The wind turbine produces about 150 watts per hour"; } else if (windSpeed >= 10.8 && windSpeed <= 13.3) { outputElement.textContent = "The wind turbine produces about 400 watts per hour"; } else if (windSpeed >= 13.4 && windSpeed <= 17.1) { outputElement.textContent = "The wind turbine produces about 50 watts per hour"; } else { outputElement.textContent = "The wind turbine produces 0 watts per hour"; } }
原代码问题及修正说明
- 命名规范错误:JavaScript变量名、HTML元素ID不能包含空格,比如
strength selected改为windSpeed,wind strength改为wind-strength,避免语法报错。 - 函数调用错误:按钮
onclick属性需写myFunction()(带括号),否则无法触发函数执行。 - 输入类型问题:输入框
value默认是字符串,直接比较会导致逻辑错误,用parseFloat()转为数字后再做范围判断。 - 条件逻辑错误:原代码
== 1.6 - 3.3会被计算为== -1.7,完全不符合区间判断需求,改用>= 最小值 && <= 最大值匹配风速范围。 - 区间重叠问题:原代码中13.4同时属于两个区间,调整为
10.8-13.3和13.4-17.1,避免逻辑冲突。 - 元素ID不统一:原代码输出元素ID混用
output value和out value,统一为output-value确保能正确获取元素。
内容的提问来源于stack exchange,提问作者chacha32
相关产品推荐
相关产品推荐

