数字和字符串 - 知蛛网数字(Number)
1. 数字表示方式
// 十进制
42;
3.14;
0.5; // 0.5
5.0; // 5
// 科学计数法
1.23e4; // 12300
1.23e-4; // 0.000123
1e6; // 1000000
// 二进制(0b 或 0B 开头)
0b1010; // 10
0b1111; // 15
// 八进制(0o 或 0O 开头)
0o755; // 493
0o777; // 511
// 十六进制(0x 或 0X 开头)
0xff; // 255
0x1a3; // 419
0xff; // 255(不区分大小写)
// 数字分隔符(ES2021+)
1_000_000; // 1000000
0b1010_0001; // 161
0xff_ff_ff; // 16777215
1_000.5_00; // 1000.5
2. 特殊数值
// Infinity 和 -Infinity
console.log(1 / 0); // Infinity
console.log(-1 / 0); // -Infinity
console.log(Infinity + 1); // Infinity
console.log(Infinity * Infinity); // Infinity
console.log(1 / Infinity); // 0
// NaN(Not a Number)
console.log(0 / 0); // NaN
console.log(Math.sqrt(-1)); // NaN
console.log("hello" * 5); // NaN
console.log(NaN === NaN); // false(唯一不等于自身的值)
console.log(Number.isNaN(NaN)); // true(正确检查方式)
// Number 对象的特殊值
console.log(Number.MAX_VALUE); // 1.7976931348623157e+308
console.log(Number.MIN_VALUE); // 5e-324
console.log(Number.MAX_SAFE_INTEGER); // 9007199254740991
console.log(Number.MIN_SAFE_INTEGER); // -9007199254740991
console.log(Number.POSITIVE_INFINITY); // Infinity
console.log(Number.NEGATIVE_INFINITY); // -Infinity
console.log(Number.EPSILON); // 2.220446049250313e-16
3. 数字精度问题
// 浮点数精度问题
console.log(0.1 + 0.2); // 0.30000000000000004
console.log(0.1 + 0.2 === 0.3); // false
// 解决方案
function areEqual(num1, num2, epsilon = Number.EPSILON) {
return Math.abs(num1 - num2) < epsilon;
}
console.log(areEqual(0.1 + 0.2, 0.3)); // true
// 或使用 toFixed(转换为字符串)
console.log((0.1 + 0.2).toFixed(1)); // "0.3"
console.log(+(0.1 + 0.2).toFixed(1)); // 0.3
// 大整数精度问题
console.log(9007199254740992 === 9007199254740993); // true(超出安全范围)
// 使用 BigInt 解决
console.log(9007199254740992n === 9007199254740993n); // false
4. Number 对象方法
// 转换方法
console.log(Number("123")); // 123
console.log(Number("123.45")); // 123.45
console.log(Number("")); // 0
console.log(Number("hello")); // NaN
console.log(Number("123px")); // NaN
console.log(Number(true)); // 1
console.log(Number(false)); // 0
console.log(Number(null)); // 0
console.log(Number(undefined)); // NaN
// 全局函数
console.log(parseInt("123")); // 123
console.log(parseInt("123.45")); // 123
console.log(parseInt("123px")); // 123
console.log(parseInt("FF", 16)); // 255(指定基数)
console.log(parseInt("010")); // 10(ES5+)
console.log(parseInt("010", 8)); // 8
console.log(parseFloat("123.45")); // 123.45
console.log(parseFloat("123.45px")); // 123.45
console.log(parseFloat("12.34.56")); // 12.34
// 检查方法
console.log(Number.isFinite(42)); // true
console.log(Number.isFinite(Infinity)); // false
console.log(Number.isFinite(NaN)); // false
console.log(Number.isInteger(42)); // true
console.log(Number.isInteger(42.0)); // true
console.log(Number.isInteger(42.5)); // false
console.log(Number.isSafeInteger(42)); // true
console.log(Number.isSafeInteger(9007199254740992)); // false
console.log(Number.isNaN(NaN)); // true
console.log(Number.isNaN("hello")); // false(与全局 isNaN 不同)
console.log(isNaN("hello")); // true(全局 isNaN 会先转换)
5. Number 原型方法
let num = 123.45678;
// 转换为字符串
console.log(num.toString()); // "123.45678"
console.log(num.toString(2)); // "1111011.011101001011110001101"(二进制)
console.log(num.toString(8)); // "173.352"(八进制)
console.log(num.toString(16)); // "7b.74bc"(十六进制)
console.log((255).toString(16)); // "ff"
// 格式化为字符串
console.log(num.toFixed(2)); // "123.46"(四舍五入)
console.log(num.toFixed(0)); // "123"
console.log(num.toFixed(5)); // "123.45678"
console.log(num.toPrecision(4)); // "123.5"(指定有效数字)
console.log(num.toPrecision(7)); // "123.4568"
console.log(num.toPrecision(2)); // "1.2e+2"
// 指数表示法
console.log(num.toExponential(2)); // "1.23e+2"
console.log(num.toExponential(4)); // "1.2346e+2"
// 本地化格式
console.log(num.toLocaleString()); // "123.457"(根据地区)
console.log(num.toLocaleString("zh-CN")); // "123.457"
console.log(num.toLocaleString("en-US")); // "123.457"
console.log(num.toLocaleString("de-DE")); // "123,457"
console.log(
(1234567.89).toLocaleString("zh-CN", {
style: "currency",
currency: "CNY",
})
); // "¥1,234,567.89"
console.log(
(0.15).toLocaleString("zh-CN", {
style: "percent",
})
); // "15%"
6. Math 对象
// 基本数学运算
console.log(Math.PI); // 3.141592653589793
console.log(Math.E); // 2.718281828459045
console.log(Math.LN2); // 0.6931471805599453
console.log(Math.LN10); // 2.302585092994046
console.log(Math.LOG2E); // 1.4426950408889634
console.log(Math.LOG10E); // 0.4342944819032518
console.log(Math.SQRT2); // 1.4142135623730951
console.log(Math.SQRT1_2); // 0.7071067811865476
// 舍入方法
console.log(Math.round(4.7)); // 5(四舍五入)
console.log(Math.round(4.4)); // 4
console.log(Math.round(4.5)); // 5
console.log(Math.ceil(4.1)); // 5(向上取整)
console.log(Math.ceil(-4.1)); // -4
console.log(Math.floor(4.9)); // 4(向下取整)
console.log(Math.floor(-4.9)); // -5
console.log(Math.trunc(4.9)); // 4(去除小数部分)
console.log(Math.trunc(-4.9)); // -4
// 最大最小值
console.log(Math.max(1, 3, 5, 2)); // 5
console.log(Math.min(1, 3, 5, 2)); // 1
const numbers = [1, 3, 5, 2];
console.log(Math.max(...numbers)); // 5(使用展开运算符)
console.log(Math.min(...numbers)); // 1
// 幂和根
console.log(Math.pow(2, 3)); // 8
console.log(2 ** 3); // 8(ES2016+)
console.log(Math.sqrt(16)); // 4
console.log(Math.cbrt(27)); // 3(立方根)
console.log(Math.hypot(3, 4)); // 5(勾股定理)
// 随机数
console.log(Math.random()); // 0到1之间的随机数
console.log(Math.floor(Math.random() * 10)); // 0-9的整数
console.log(Math.floor(Math.random() * 10) + 1); // 1-10的整数
// 三角函数(参数为弧度)
console.log(Math.sin(Math.PI / 2)); // 1
console.log(Math.cos(Math.PI)); // -1
console.log(Math.tan(Math.PI / 4)); // 0.9999999999999999
// 角度与弧度转换
function toRadians(degrees) {
return (degrees * Math.PI) / 180;
}
function toDegrees(radians) {
return (radians * 180) / Math.PI;
}
// 其他数学函数
console.log(Math.abs(-5)); // 5(绝对值)
console.log(Math.sign(-5)); // -1(符号函数)
console.log(Math.sign(0)); // 0
console.log(Math.sign(5)); // 1
console.log(Math.exp(1)); // 2.718...(e的幂)
console.log(Math.log(Math.E)); // 1(自然对数)
console.log(Math.log10(100)); // 2(以10为底的对数)
console.log(Math.log2(8)); // 3(以2为底的对数)
7. BigInt(ES2020+)
// 创建 BigInt
const big1 = 1234567890123456789012345678901234567890n;
const big2 = BigInt("123456789012345678901234567890");
const big3 = BigInt(1234567890);
// 运算(大多数运算符与 Number 相同)
console.log(big1 + big2); // 加法
console.log(big1 - big2); // 减法
console.log(big1 * big2); // 乘法
console.log(big1 / big2); // 除法(结果为整数)
console.log(big1 % big2); // 取余
console.log(big1 ** 2n); // 幂运算
// 比较运算
console.log(1n === 1); // false(类型不同)
console.log(1n == 1); // true(值相等)
console.log(1n < 2); // true
console.log(2n > 1); // true
// 位运算(除 >>> 外)
console.log(5n & 3n); // 1n
console.log(5n | 3n); // 7n
console.log(5n ^ 3n); // 6n
console.log(~5n); // -6n
console.log(5n << 1n); // 10n
// 类型转换
console.log(Number(123n)); // 123(可能丢失精度)
console.log(String(123n)); // "123"
console.log(Boolean(0n)); // false
console.log(Boolean(1n)); // true
// 不能与 Number 混合运算
// console.log(1n + 2); // TypeError
console.log(1n + BigInt(2)); // 3n
// 方法
console.log(123n.toString()); // "123"
console.log(123n.toString(2)); // "1111011"(二进制)
字符串(String)
1. 字符串创建
// 字符串字面量
const single = "单引号字符串";
const double = "双引号字符串";
const backtick = `反引号字符串(模板字面量)`;
// 字符串构造函数
const str1 = new String("Hello"); // String对象
const str2 = String("Hello"); // 原始字符串
console.log(typeof str1); // "object"
console.log(typeof str2); // "string"
// 转义字符
const escaped = 'He said: "Hello!"'; // 双引号在单引号字符串中不需要转义
const escaped2 = 'He said: "Hello!"'; // 需要转义
const escaped3 = "Line 1\nLine 2"; // \n 换行
const escaped4 = "Tab\there"; // \t 制表符
const escaped5 = "Backslash: \\"; // \\ 反斜杠
console.log("\u0041"); // "A"(Unicode转义)
console.log("\u{1F60A}"); // "😊"(ES6 Unicode码点)
console.log("\x41"); // "A"(十六进制转义)
2. 模板字面量(ES6+)
// 基本插值
const name = "张三";
const age = 25;
const greeting = `你好,${name}!你今年${age}岁了。`;
console.log(greeting); // "你好,张三!你今年25岁了。"
// 表达式计算
const a = 5,
b = 10;
console.log(`${a} + ${b} = ${a + b}`); // "5 + 10 = 15"
// 多行字符串
const multiLine = `第一行
第二行
第三行`;
console.log(multiLine);
// 嵌套模板
const isMember = true;
const discount = isMember ? `(会员享受${10}%折扣)` : "";
console.log(`总价:100元${discount}`);
// 标签模板
function highlight(strings, ...values) {
return strings.reduce((result, str, i) => {
const value = values[i] ? `<strong>${values[i]}</strong>` : "";
return result + str + value;
}, "");
}
const user = "张三";
const score = 95;
const result = highlight`用户 ${user} 的得分是 ${score} 分`;
console.log(result); // "用户 <strong>张三</strong> 的得分是 <strong>95</strong> 分"
// 原始字符串(不处理转义)
const path = String.raw`C:\Users\Documents\file.txt`;
console.log(path); // "C:\Users\Documents\file.txt"(\不转义)
3. 字符串基本操作
const str = "Hello World";
// 访问字符
console.log(str[0]); // "H"(ES5+)
console.log(str.charAt(0)); // "H"
console.log(str.charAt(100)); // ""(不会报错)
console.log(str[100]); // undefined
// 字符串长度
console.log(str.length); // 11
// 遍历字符串
for (let i = 0; i < str.length; i++) {
console.log(str[i]);
}
for (let char of str) {
console.log(char);
}
// 不可变性(字符串不可修改)
let myStr = "hello";
myStr[0] = "H"; // 无效
console.log(myStr); // "hello"
// 只能重新赋值
myStr = "H" + myStr.slice(1);
console.log(myStr); // "Hello"
4. 字符串查找
const str = "Hello World, welcome to the world of JavaScript";
// indexOf / lastIndexOf
console.log(str.indexOf("World")); // 6
console.log(str.indexOf("world")); // 23(区分大小写)
console.log(str.indexOf("o")); // 4(第一个)
console.log(str.lastIndexOf("o")); // 29(最后一个)
console.log(str.indexOf("o", 10)); // 17(从索引10开始找)
console.log(str.indexOf("xyz")); // -1(未找到)
// includes(ES6+)
console.log(str.includes("World")); // true
console.log(str.includes("world")); // true
console.log(str.includes("World", 10)); // false(从索引10开始)
// startsWith / endsWith(ES6+)
console.log(str.startsWith("Hello")); // true
console.log(str.startsWith("World", 6)); // true(从索引6开始)
console.log(str.endsWith("JavaScript")); // true
console.log(str.endsWith("World", 11)); // true(只考虑前11个字符)
// search(正则表达式)
console.log(str.search(/world/i)); // 6(不区分大小写)
console.log(str.search(/[0-9]/)); // -1(没找到数字)
// match
console.log(str.match(/world/gi)); // ["World", "world"]
const match = str.match(/world/i);
console.log(match[0]); // "World"
console.log(match.index); // 6
// matchAll(ES2020+)
const regex = /world/gi;
const matches = [...str.matchAll(regex)];
console.log(matches[0][0]); // "World"
console.log(matches[0].index); // 6
console.log(matches[1][0]); // "world"
console.log(matches[1].index); // 23
5. 字符串修改
// concat(不修改原字符串)
const str1 = "Hello";
const str2 = "World";
console.log(str1.concat(" ", str2)); // "Hello World"
console.log(str1); // "Hello"(未修改)
// slice / substring / substr
const str = "Hello World";
console.log(str.slice(6, 11)); // "World"
console.log(str.slice(6)); // "World"
console.log(str.slice(-5)); // "World"(倒数)
console.log(str.slice(-5, -1)); // "Worl"
console.log(str.substring(6, 11)); // "World"
console.log(str.substring(11, 6)); // "World"(自动交换参数)
console.log(str.substring(-3)); // "Hello World"(负值视为0)
console.log(str.substr(6, 5)); // "World"
console.log(str.substr(6)); // "World"
console.log(str.substr(-5)); // "World"(倒数)
// 注意区别
const example = "abcdef";
console.log(example.slice(2, -1)); // "cde"(从2到倒数第1)
console.log(example.substring(2, -1)); // "ab"(-1转为0,然后交换)
console.log(example.substr(2, -1)); // ""(负长度转为空)
// repeat(ES6+)
console.log("Ha".repeat(3)); // "HaHaHa"
console.log("Ha".repeat(0)); // ""
console.log("Ha".repeat(2.5)); // "HaHa"(向下取整)
// padStart / padEnd(ES2017+)
console.log("5".padStart(3, "0")); // "005"
console.log("5".padEnd(3, "0")); // "500"
console.log("abc".padStart(10, "123")); // "1231231abc"
console.log("abc".padStart(6)); // " abc"(默认空格)
// trim / trimStart / trimEnd(ES2019+)
const spaced = " Hello World ";
console.log(spaced.trim()); // "Hello World"
console.log(spaced.trimStart()); // "Hello World "
console.log(spaced.trimEnd()); // " Hello World"
6. 字符串替换
const str = "Hello World, world is beautiful";
// replace(只替换第一个)
console.log(str.replace("world", "Earth")); // "Hello World, Earth is beautiful"
console.log(str.replace(/world/i, "Earth")); // "Hello Earth, world is beautiful"
// replaceAll(ES2021+)
console.log(str.replaceAll("world", "Earth")); // "Hello World, Earth is beautiful"
console.log(str.replaceAll(/world/gi, "Earth")); // "Hello Earth, Earth is beautiful"
// 使用函数进行替换
console.log(
str.replace(/\w+/g, word => {
return word.toUpperCase();
})
); // "HELLO WORLD, WORLD IS BEAUTIFUL"
// 捕获组替换
const date = "2024-01-15";
console.log(date.replace(/(\d{4})-(\d{2})-(\d{2})/, "$2/$3/$1")); // "01/15/2024"
// 拆分与连接
const csv = "apple,banana,orange,grape";
const fruits = csv.split(",");
console.log(fruits); // ["apple", "banana", "orange", "grape"]
console.log(fruits.join(";")); // "apple;banana;orange;grape"
console.log("Hello World".split(" ")); // ["Hello", "World"]
console.log("Hello".split("")); // ["H", "e", "l", "l", "o"]
console.log("Hello".split("", 3)); // ["H", "e", "l"](限制返回数量)
7. 字符串大小写转换
const str = "Hello World";
console.log(str.toLowerCase()); // "hello world"
console.log(str.toUpperCase()); // "HELLO WORLD"
// 首字母大写
function capitalize(str) {
return str.charAt(0).toUpperCase() + str.slice(1).toLowerCase();
}
console.log(capitalize("hello")); // "Hello"
// 标题化(每个单词首字母大写)
function toTitleCase(str) {
return str.toLowerCase().replace(/\b\w/g, char => char.toUpperCase());
}
console.log(toTitleCase("hello world javascript")); // "Hello World JavaScript"
// 特定语言的大小写转换
console.log("İstanbul".toLocaleLowerCase("tr-TR")); // "istanbul"
console.log("istanbul".toLocaleUpperCase("tr-TR")); // "İSTANBUL"
8. 字符串比较与排序
// 基本比较(基于Unicode码点)
console.log("a" < "b"); // true
console.log("A" < "a"); // true(大写字母码点较小)
console.log("10" < "2"); // true(字符串比较,'1' < '2')
// 区域敏感比较
console.log("ä".localeCompare("z", "de")); // -1(德语中ä在z之前)
console.log("ä".localeCompare("z", "sv")); // 1(瑞典语中ä在z之后)
// 排序数组
const words = ["apple", "Banana", "cherry", "Date"];
words.sort(); // ["Banana", "Date", "apple", "cherry"](默认)
words.sort((a, b) => a.localeCompare(b)); // ["apple", "Banana", "cherry", "Date"]
// 带选项的比较
console.log(
"résumé".localeCompare("resume", "en", {
sensitivity: "base", // 忽略大小写和重音
})
); // 0(相等)
// 数字字符串排序
const numbers = ["10", "2", "1", "20"];
numbers.sort(); // ["1", "10", "2", "20"](字符串排序)
numbers.sort((a, b) => a - b); // ["1", "2", "10", "20"](数字排序)
9. 字符串编码与解码
// Base64 编码解码
const str = "Hello World";
const encoded = btoa(str); // "SGVsbG8gV29ybGQ="
const decoded = atob(encoded); // "Hello World"
// URI 编码解码
const url = "https://example.com/测试页面?name=张三&age=25";
console.log(encodeURI(url));
// "https://example.com/%E6%B5%8B%E8%AF%95%E9%A1%B5%E9%9D%A2?name=%E5%BC%A0%E4%B8%89&age=25"
console.log(encodeURIComponent(url));
// "https%3A%2F%2Fexample.com%2F%E6%B5%8B%E8%AF%95%E9%A1%B5%E9%9D%A2%3Fname%3D%E5%BC%A0%E4%B8%89%26age%3D25"
// 区别:encodeURI用于完整URL,encodeURIComponent用于URL部分
// Unicode 编码
console.log("A".charCodeAt(0)); // 65(UTF-16码点)
console.log("😊".charCodeAt(0)); // 55357(代理对第一部分)
// 码点相关方法(ES6+)
console.log("😊".codePointAt(0)); // 128522(完整码点)
console.log(String.fromCodePoint(128522)); // "😊"
console.log("😊".charCodeAt(0).toString(16)); // "d83d"
console.log("😊".codePointAt(0).toString(16)); // "1f60a"
// 代理对检测
function isSurrogatePair(str, index) {
const code = str.charCodeAt(index);
return code >= 0xd800 && code <= 0xdbff;
}
// 正确遍历包含表情符号的字符串
const text = "Hello 😊 World";
for (let char of text) {
console.log(char);
}
// "H", "e", "l", "l", "o", " ", "😊", " ", "W", "o", "r", "l", "d"
10. 字符串性能优化
// 1. 避免在循环中使用字符串连接(使用数组)
// 不好
let result = "";
for (let i = 0; i < 10000; i++) {
result += "x"; // 每次创建新字符串
}
// 好
let parts = [];
for (let i = 0; i < 10000; i++) {
parts.push("x");
}
let result2 = parts.join("");
// 2. 使用模板字面量代替连接
const name = "张三";
const age = 25;
// 不好
const greeting1 = "你好," + name + ",你今年" + age + "岁了";
// 好
const greeting2 = `你好,${name},你今年${age}岁了`;
// 3. 使用正则表达式优化多次操作
const text = "a,b,c,d,e";
// 不好
let replaced = text.replace("a", "A").replace("b", "B").replace("c", "C");
// 好
let replaced2 = text.replace(/[abc]/g, match => {
return match.toUpperCase();
});
// 4. 缓存字符串长度
const longString = "very long string...";
for (let i = 0, len = longString.length; i < len; i++) {
// 使用缓存的长度
}
// 5. 使用字符串插值而不是方法链
// 不好
const fullName = firstName.concat(" ").concat(lastName);
// 好
const fullName2 = `${firstName} ${lastName}`;
11. 实用字符串函数库
// 常用字符串工具函数集合
const StringUtils = {
// 生成随机字符串
random(length = 8, chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789") {
let result = "";
for (let i = 0; i < length; i++) {
result += chars.charAt(Math.floor(Math.random() * chars.length));
}
return result;
},
// 格式化字符串(类似 printf)
format(template, ...args) {
return template.replace(/{(\d+)}/g, (match, index) => {
return typeof args[index] !== "undefined" ? args[index] : match;
});
},
// 移除HTML标签
stripHtml(html) {
return html.replace(/<[^>]*>/g, "");
},
// 截断字符串并添加省略号
truncate(str, length, suffix = "...") {
if (str.length <= length) return str;
return str.substring(0, length - suffix.length) + suffix;
},
// 检查字符串是否为数字
isNumeric(str) {
return !isNaN(parseFloat(str)) && isFinite(str);
},
// 生成UUID
uuid() {
return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function (c) {
const r = (Math.random() * 16) | 0;
const v = c === "x" ? r : (r & 0x3) | 0x8;
return v.toString(16);
});
},
// 驼峰转换
camelCase(str) {
return str.toLowerCase().replace(/[^a-zA-Z0-9]+(.)/g, (match, char) => {
return char.toUpperCase();
});
},
// 下划线转换
snakeCase(str) {
return str.replace(/[A-Z]/g, match => "_" + match.toLowerCase()).replace(/^_/, "");
},
// 统计字符出现次数
countOccurrences(str, char) {
return str.split(char).length - 1;
},
// 反转字符串
reverse(str) {
return [...str].reverse().join("");
},
// 判断是否为回文
isPalindrome(str) {
const clean = str.toLowerCase().replace(/[^a-z0-9]/g, "");
return clean === this.reverse(clean);
},
};
// 使用示例
console.log(StringUtils.format("Hello {0}, you have {1} messages.", "Alice", 5));
// "Hello Alice, you have 5 messages."
console.log(StringUtils.truncate("This is a very long string", 10));
// "This is a..."
console.log(StringUtils.camelCase("hello_world_test"));
// "helloWorldTest"
console.log(StringUtils.uuid());
// "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx"
数字与字符串转换
// 数字转字符串
const num = 123.456;
console.log(num.toString()); // "123.456"
console.log(String(num)); // "123.456"
console.log(num + ""); // "123.456"
console.log(`${num}`); // "123.456"
// 格式化数字字符串
console.log(num.toFixed(2)); // "123.46"
console.log(num.toPrecision(4)); // "123.5"
console.log(num.toExponential(2)); // "1.23e+2"
// 字符串转数字
const str = "123.45";
console.log(Number(str)); // 123.45
console.log(parseFloat(str)); // 123.45
console.log(parseInt(str)); // 123
console.log(+str); // 123.45
console.log(str * 1); // 123.45
console.log(str - 0); // 123.45
// 解析不同进制的字符串
console.log(parseInt("1010", 2)); // 10(二进制)
console.log(parseInt("FF", 16)); // 255(十六进制)
console.log(parseInt("077", 8)); // 63(八进制)
// 安全的数字转换
function safeToNumber(str, defaultValue = 0) {
const num = Number(str);
return Number.isNaN(num) ? defaultValue : num;
}
console.log(safeToNumber("123")); // 123
console.log(safeToNumber("abc")); // 0
console.log(safeToNumber("abc", 100)); // 100
最佳实践
1. 处理大数字
// 使用 BigInt 处理超出安全范围的整数
const bigNumber = BigInt("12345678901234567890");
console.log(bigNumber.toString());
// 格式化大数字
function formatLargeNumber(num) {
if (num >= 1e12) return (num / 1e12).toFixed(1) + "T";
if (num >= 1e9) return (num / 1e9).toFixed(1) + "B";
if (num >= 1e6) return (num / 1e6).toFixed(1) + "M";
if (num >= 1e3) return (num / 1e3).toFixed(1) + "K";
return num.toString();
}
console.log(formatLargeNumber(1234567890)); // "1.2B"
2. 处理用户输入
// 安全处理用户输入的数字
function sanitizeNumberInput(input) {
// 移除非数字字符(保留小数点和负号)
const cleaned = input.replace(/[^\d.-]/g, "");
const num = parseFloat(cleaned);
// 检查是否有效
if (Number.isNaN(num)) {
throw new Error("Invalid number input");
}
// 限制范围
const MIN = 0;
const MAX = 100;
return Math.min(Math.max(num, MIN), MAX);
}
// 处理多语言数字输入
function parseLocalizedNumber(str, locale = "en-US") {
const thousandSeparator = (1000).toLocaleString(locale)[1];
const decimalSeparator = (1.1).toLocaleString(locale)[1];
// 移除千位分隔符,标准化小数分隔符
const normalized = str
.replace(new RegExp(`\\${thousandSeparator}`, "g"), "")
.replace(new RegExp(`\\${decimalSeparator}`), ".");
return parseFloat(normalized);
}
console.log(parseLocalizedNumber("1.234,56", "de-DE")); // 1234.56
3. 性能敏感操作
// 使用 TextDecoder/TextEncoder 处理大量文本
const encoder = new TextEncoder();
const decoder = new TextDecoder();
const text = "Hello World";
const encoded = encoder.encode(text);
const decoded = decoder.decode(encoded);
// 使用 ArrayBuffer 优化字符串操作
function concatenateStrings(strings) {
const totalLength = strings.reduce((sum, str) => sum + str.length, 0);
const buffer