เราจำเป็นต้องเขียนฟังก์ชัน 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