返回
JavaScript 函数:9 大神器,玩转前端开发
前端
2023-10-31 13:58:39
JavaScript 函数是 JavaScript 语言的基本构建块,它允许你将代码组织成可重用的单元,以便在程序中多次调用。函数可以定义在其他函数内部,称为嵌套函数。函数可以定义在其他函数内部,称为嵌套函数。函数可以定义在其他函数内部,称为嵌套函数。函数可以定义在其他函数内部,称为嵌套函数。函数可以定义在其他函数内部,称为嵌套函数。
1. console.log() 函数
console.log() 函数用于在控制台中输出信息。它可以输出任何类型的数据,包括字符串、数字、布尔值、数组、对象等。
console.log("Hello, world!");
console.log(123);
console.log(true);
console.log([1, 2, 3]);
console.log({name: "John Doe", age: 30});
2. parseInt() 函数
parseInt() 函数将字符串转换为整数。如果字符串不能转换为整数,则返回 NaN。
const num1 = parseInt("123"); // num1 = 123
const num2 = parseInt("456.789"); // num2 = 456
const num3 = parseInt("abc"); // num3 = NaN
3. parseFloat() 函数
parseFloat() 函数将字符串转换为浮点数。如果字符串不能转换为浮点数,则返回 NaN。
const num1 = parseFloat("123.45"); // num1 = 123.45
const num2 = parseFloat("456"); // num2 = 456
const num3 = parseFloat("abc"); // num3 = NaN
4. Math.random() 函数
Math.random() 函数返回一个介于 0 和 1 之间的随机数。
const randomNumber = Math.random(); // randomNumber = 0.123456789
5. Date() 函数
Date() 函数返回当前日期和时间。
const date = new Date(); // date = Sun Oct 16 2022 15:03:21 GMT+0800 (中国标准时间)
6. Array.push() 函数
Array.push() 函数将一个或多个元素添加到数组的末尾。
const array = [1, 2, 3];
array.push(4, 5, 6); // array = [1, 2, 3, 4, 5, 6]
7. Array.pop() 函数
Array.pop() 函数从数组的末尾删除最后一个元素并返回该元素。
const array = [1, 2, 3];
const lastElement = array.pop(); // lastElement = 3
console.log(array); // array = [1, 2]
8. Array.shift() 函数
Array.shift() 函数从数组的开头删除第一个元素并返回该元素。
const array = [1, 2, 3];
const firstElement = array.shift(); // firstElement = 1
console.log(array); // array = [2, 3]
9. Array.unshift() 函数
Array.unshift() 函数向数组的开头添加一个或多个元素。
const array = [1, 2, 3];
array.unshift(4, 5, 6); // array = [4, 5, 6, 1, 2, 3]
以上 9 个函数是 JavaScript 中最常用的函数,掌握它们可以让你事半功倍。请多多练习,将这些函数熟练运用到你的项目中去。