js实现单位转化
单位转换实现方法
在JavaScript中实现单位转换通常涉及数学运算和格式化输出。以下是几种常见的单位转换场景及实现方式:
长度单位转换
function convertLength(value, fromUnit, toUnit) {
const units = {
mm: 1,
cm: 10,
m: 1000,
km: 1000000,
in: 25.4,
ft: 304.8,
yd: 914.4,
mi: 1609344
};
return (value * units[fromUnit]) / units[toUnit];
}
// 示例:将5英尺转换为米
console.log(convertLength(5, 'ft', 'm')); // 1.524
温度单位转换
function convertTemperature(value, fromUnit, toUnit) {
if (fromUnit === 'C' && toUnit === 'F') {
return value * 9/5 + 32;
}
if (fromUnit === 'F' && toUnit === 'C') {
return (value - 32) * 5/9;
}
if (fromUnit === 'K' && toUnit === 'C') {
return value - 273.15;
}
// 其他转换组合...
return value;
}
// 示例:将100℃转换为℉
console.log(convertTemperature(100, 'C', 'F')); // 212
重量单位转换
function convertWeight(value, fromUnit, toUnit) {
const units = {
mg: 0.001,
g: 1,
kg: 1000,
oz: 28.3495,
lb: 453.592,
ton: 907185
};
return (value * units[fromUnit]) / units[toUnit];
}
// 示例:将1磅转换为克
console.log(convertWeight(1, 'lb', 'g')); // 453.592
时间单位转换
function convertTime(value, fromUnit, toUnit) {
const units = {
ms: 1,
s: 1000,
min: 60000,
h: 3600000,
d: 86400000,
wk: 604800000
};
return (value * units[fromUnit]) / units[toUnit];
}
// 示例:将1天转换为小时
console.log(convertTime(1, 'd', 'h')); // 24
货币转换实现
货币转换通常需要实时汇率数据:
async function convertCurrency(amount, fromCurrency, toCurrency) {
const apiKey = 'YOUR_API_KEY';
const response = await fetch(`https://api.exchangerate-api.com/v4/latest/${fromCurrency}`);
const data = await response.json();
return amount * data.rates[toCurrency];
}
// 示例:将100美元转换为欧元
convertCurrency(100, 'USD', 'EUR').then(console.log);
通用单位转换类
可以创建一个更通用的单位转换类:

class UnitConverter {
constructor() {
this.conversions = {
length: { mm:1, cm:10, m:1000, km:1000000 },
weight: { mg:1, g:1000, kg:1000000 },
// 其他单位类型...
};
}
convert(value, fromUnit, toUnit, type) {
const units = this.conversions[type];
return (value * units[fromUnit]) / units[toUnit];
}
}
const converter = new UnitConverter();
console.log(converter.convert(1, 'm', 'cm', 'length')); // 100
注意事项
- 浮点数精度问题需要考虑,可以使用
toFixed()方法控制小数位数 - 对于货币转换等需要实时数据的场景,应该处理API请求失败的情况
- 可以扩展支持更多单位类型和转换组合
- 复杂的单位系统可能需要更复杂的转换公式
以上方法提供了JavaScript中实现常见单位转换的基本模式,可以根据具体需求进行调整和扩展。






