全局函数与全局变量
JavaScript 内置的全局函数和全局变量汇总
问题
JavaScript 中有哪些全局函数和全局变量?
解答
全局变量
// Infinity - 表示无穷大
console.log(Infinity); // Infinity
console.log(1 / 0); // Infinity
// NaN - 表示非数字
console.log(NaN); // NaN
console.log(0 / 0); // NaN
// undefined - 表示未定义
let a;
console.log(a); // undefined
// globalThis - 全局对象引用(ES2020)
console.log(globalThis); // 浏览器中是 window,Node 中是 global
全局函数
// 1. 类型转换函数
parseInt('123px'); // 123
parseInt('0xF', 16); // 15
parseFloat('3.14abc'); // 3.14
// 2. 数值判断函数
isNaN(NaN); // true
isNaN('hello'); // true(会先转换为数字)
isFinite(100); // true
isFinite(Infinity); // false
// 3. URI 编码/解码函数
const url = 'https://example.com?name=张三';
// encodeURI - 编码整个 URI,保留特殊字符(: / ? & =)
encodeURI(url); // "https://example.com?name=%E5%BC%A0%E4%B8%89"
// encodeURIComponent - 编码 URI 组件,编码所有特殊字符
encodeURIComponent(url); // "https%3A%2F%2Fexample.com%3Fname%3D%E5%BC%A0%E4%B8%89"
// decodeURI / decodeURIComponent - 对应的解码函数
decodeURI('%E5%BC%A0%E4%B8%89'); // "张三"
decodeURIComponent('%3A%2F%2F'); // "://"
// 4. eval - 执行字符串代码(不推荐使用)
eval('1 + 2'); // 3
全局函数一览表
| 函数 | 作用 |
|---|---|
parseInt() | 字符串转整数 |
parseFloat() | 字符串转浮点数 |
isNaN() | 判断是否为 NaN |
isFinite() | 判断是否为有限数 |
encodeURI() | 编码 URI |
decodeURI() | 解码 URI |
encodeURIComponent() | 编码 URI 组件 |
decodeURIComponent() | 解码 URI 组件 |
eval() | 执行字符串代码 |
关键点
- 全局变量:
Infinity、NaN、undefined、globalThis parseInt第二个参数是进制,建议始终传入isNaN()会先做类型转换,Number.isNaN()不会encodeURI用于编码完整 URL,encodeURIComponent用于编码查询参数- 避免使用
eval(),存在安全风险和性能问题
目录