TypeScript 将字符串转换为数字:使用 parseInt 函数
在 TypeScript 中,你可以使用 'parseInt' 函数将字符串转换为数字。例如:
const str = '123456';
const num = parseInt(str);
console.log(num); // 输出:123456
请注意,'parseInt' 函数会尝试将字符串转换为整数,如果无法转换,它会返回 'NaN'。如果你确定字符串中只包含数字字符,可以将第二个参数传递给 'parseInt' 函数以指定基数(默认为 10)。例如:
const str = '123456';
const num = parseInt(str, 10);
console.log(num); // 输出:123456
这样可以确保正确解析字符串。
原文地址: https://www.cveoy.top/t/topic/0bT 著作权归作者所有。请勿转载和采集!