使用 JavaScript 的温度转换器
javascriptweb developmentfront end technologyobject oriented programming更新于 2025/12/11 15:40:17
我们需要编写一个 JavaScript 函数,该函数接受一个表示摄氏温度或华氏温度的字符串。
像这样 −
"23F", "43C", "23F"
我们需要编写一个 JavaScript 函数,该函数接受此字符串并将温度从摄氏温度转换为华氏温度,将华氏温度转换为摄氏温度。
示例
以下是代码 −
const temp1 = '37C';
const temp2 = '100F';
const tempConverter = temp => {
const degree = temp[temp.length-1];
let converted;
if(degree === "C") {
converted = (parseInt(temp) * 9 / 5 + 32).toFixed(2) + "F";
}else {
converted = ((parseInt(temp) -32) * 5 / 9).toFixed(2) + "C";
};
return converted;
};
console.log(tempConverter(temp1));
console.log(tempConverter(temp2));
输出
以下是控制台中的输出 −
98.60F 37.78C
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

