系统函数
本章将详细介绍ECMAScript中内置的全局函数和常用方法,这些函数提供了处理数据、执行计算、控制程序流程等核心功能。
9.1 全局函数概述
全局函数是ECMAScript环境中可以直接调用的函数,无需通过对象来访问。它们提供了各种实用功能,是JavaScript编程的基础。
9.2 类型转换函数
这些函数用于将值转换为特定的数据类型。
parseInt()函数
// parseInt()函数将字符串转换为整数
let num1 = parseInt("42"); // 42
let num2 = parseInt("42.5"); // 42
let num3 = parseInt("1010", 2); // 10 (二进制转十进制)
let num4 = parseInt("FF", 16); // 255 (十六进制转十进制)
let num5 = parseInt("hello"); // NaN
console.log(num1, num2, num3, num4, num5);
parseFloat()函数
// parseFloat()函数将字符串转换为浮点数
let num1 = parseFloat("3.14159"); // 3.14159
let num2 = parseFloat("3.14.15"); // 3.14 (遇到第二个小数点停止)
let num3 = parseFloat("10.5hello"); // 10.5
let num4 = parseFloat("hello"); // NaN
console.log(num1, num2, num3, num4);
Number()函数
// Number()函数将值转换为数字
let num1 = Number("42"); // 42
let num2 = Number("3.14"); // 3.14
let num3 = Number(true); // 1
let num4 = Number(false); // 0
let num5 = Number(null); // 0
let num6 = Number(undefined); // NaN
let num7 = Number("hello"); // NaN
console.log(num1, num2, num3, num4, num5, num6, num7);
String()函数
// String()函数将值转换为字符串
let str1 = String(42); // "42"
let str2 = String(true); // "true"
let str3 = String(null); // "null"
let str4 = String(undefined); // "undefined"
let str5 = String({}); // "[object Object]"
console.log(str1, str2, str3, str4, str5);
Boolean()函数
// Boolean()函数将值转换为布尔值
let bool1 = Boolean("hello"); // true
let bool2 = Boolean(0); // false
let bool3 = Boolean([]); // true (空数组为true)
let bool4 = Boolean({}); // true (空对象为true)
let bool5 = Boolean(""); // false
console.log(bool1, bool2, bool3, bool4, bool5);
9.3 编码和解码函数
这些函数用于处理URL编码和Unicode编码。
encodeURI()和decodeURI()函数
// encodeURI()编码完整的URI
let uri = "https://example.com/search?q=hello world";
let encodedURI = encodeURI(uri);
console.log(encodedURI); // "https://example.com/search?q=hello%20world"
// decodeURI()解码URI
let decodedURI = decodeURI(encodedURI);
console.log(decodedURI); // "https://example.com/search?q=hello world"
encodeURIComponent()和decodeURIComponent()函数
// encodeURIComponent()编码URI组件
let param = "hello world & special chars!";
let encodedParam = encodeURIComponent(param);
console.log(encodedParam); // "hello%20world%20%26%20special%20chars%21"
// decodeURIComponent()解码URI组件
let decodedParam = decodeURIComponent(encodedParam);
console.log(decodedParam); // "hello world & special chars!"
9.4 数学函数
Math对象提供了各种数学计算函数。
基本数学函数
// 绝对值
console.log(Math.abs(-5)); // 5
// 向上取整
console.log(Math.ceil(4.2)); // 5
// 向下取整
console.log(Math.floor(4.8)); // 4
// 四舍五入
console.log(Math.round(4.5)); // 5
console.log(Math.round(4.4)); // 4
// 截断小数部分
console.log(Math.trunc(4.8)); // 4
// 最大值和最小值
console.log(Math.max(1, 5, 3, 9, 2)); // 9
console.log(Math.min(1, 5, 3, 9, 2)); // 1
幂和根函数
// 幂运算
console.log(Math.pow(2, 3)); // 8 (2的3次方)
console.log(Math.pow(4, 0.5)); // 2 (4的平方根)
// 平方根
console.log(Math.sqrt(16)); // 4
// 立方根
console.log(Math.cbrt(27)); // 3
// 指数函数
console.log(Math.exp(1)); // 2.718281828459045 (e的1次方)
对数函数
// 自然对数
console.log(Math.log(Math.E)); // 1
// 以10为底的对数
console.log(Math.log10(100)); // 2
// 以2为底的对数
console.log(Math.log2(8)); // 3
三角函数
// 正弦、余弦、正切
console.log(Math.sin(Math.PI / 2)); // 1
console.log(Math.cos(0)); // 1
console.log(Math.tan(Math.PI / 4)); // 1
// 反三角函数
console.log(Math.asin(1)); // 1.5707963267948966 (π/2)
console.log(Math.acos(0)); // 1.5707963267948966 (π/2)
console.log(Math.atan(1)); // 0.7853981633974483 (π/4)
随机数函数
// 生成0到1之间的随机数
console.log(Math.random());
// 生成指定范围的随机整数
function randomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
console.log(randomInt(1, 10)); // 1到10之间的随机整数
9.5 数组函数
Array对象和数组实例提供了丰富的操作方法。
数组创建函数
// Array.of()创建数组
let arr1 = Array.of(1, 2, 3); // [1, 2, 3]
let arr2 = Array.of(5); // [5] (不是长度为5的数组)
// Array.from()从类数组对象创建数组
let arr3 = Array.from("hello"); // ['h', 'e', 'l', 'l', 'o']
let arr4 = Array.from({length: 3}, (v, i) => i); // [0, 1, 2]
数组检测函数
// Array.isArray()检测是否为数组
console.log(Array.isArray([])); // true
console.log(Array.isArray({})); // false
console.log(Array.isArray("hello")); // false
9.6 对象函数
Object对象提供了操作对象的各种方法。
对象属性操作
let obj = {name: "张三", age: 25};
// Object.keys()获取对象的所有键
console.log(Object.keys(obj)); // ['name', 'age']
// Object.values()获取对象的所有值
console.log(Object.values(obj)); // ['张三', 25]
// Object.entries()获取对象的键值对数组
console.log(Object.entries(obj)); // [['name', '张三'], ['age', 25]]
// Object.assign()合并对象
let target = {a: 1};
let source1 = {b: 2};
let source2 = {c: 3};
Object.assign(target, source1, source2);
console.log(target); // {a: 1, b: 2, c: 3}
对象属性描述符
let obj = {};
// Object.defineProperty()定义属性
Object.defineProperty(obj, 'name', {
value: '张三',
writable: false, // 不可写
enumerable: true, // 可枚举
configurable: false // 不可配置
});
console.log(obj.name); // "张三"
// obj.name = "李四"; // 严格模式下会报错
// Object.getOwnPropertyDescriptor()获取属性描述符
let descriptor = Object.getOwnPropertyDescriptor(obj, 'name');
console.log(descriptor);
9.7 JSON函数
JSON对象提供了JSON数据的解析和序列化功能。
// JSON.stringify()将对象序列化为JSON字符串
let obj = {name: "张三", age: 25};
let jsonStr = JSON.stringify(obj);
console.log(jsonStr); // '{"name":"张三","age":25}'
// JSON.parse()将JSON字符串解析为对象
let parsedObj = JSON.parse(jsonStr);
console.log(parsedObj.name); // "张三"
// 格式化输出
let formattedJson = JSON.stringify(obj, null, 2);
console.log(formattedJson);
/*
{
"name": "张三",
"age": 25
}
*/
9.8 其他实用函数
定时器函数
// setTimeout()延迟执行
let timeoutId = setTimeout(() => {
console.log("延迟执行");
}, 1000);
// clearTimeout()取消延迟执行
// clearTimeout(timeoutId);
// setInterval()定时执行
let intervalId = setInterval(() => {
console.log("定时执行");
}, 2000);
// clearInterval()取消定时执行
// clearInterval(intervalId);
控制台函数
// console.log()输出信息
console.log("普通信息");
// console.error()输出错误信息
console.error("错误信息");
// console.warn()输出警告信息
console.warn("警告信息");
// console.info()输出信息
console.info("信息");
// console.table()以表格形式输出
console.table([{name: "张三", age: 25}, {name: "李四", age: 30}]);
9.9 函数式编程相关函数
ES6+引入了一些支持函数式编程的新函数。
函数绑定
// bind()函数绑定this值
let obj = {name: "张三"};
function greet() {
return `你好, ${this.name}!`;
}
let boundGreet = greet.bind(obj);
console.log(boundGreet()); // "你好, 张三!"
提示:熟练掌握这些系统函数可以大大提高开发效率。在实际开发中,应该根据具体需求选择合适的函数,并注意函数的浏览器兼容性。