JS中的函数、对象和数组
发布: (2025年12月25日 GMT+8 15:00)
2 min read
原文: Dev.to
Source: Dev.to
函数
函数是一段执行特定任务并且可以重复使用的代码块。JavaScript 中定义函数有三种方式:
- 函数声明
- 函数表达式
- 箭头函数(ES6) – 语法简洁,常用于现代 JS。
示例
// Function Declaration
function greet(name) {
return "Hello " + name;
}
console.log(greet("Ajmal"));
// Function Expression
const add = function (a, b) {
return a + b;
};
console.log(add(5, 3));
// Arrow Function
const multiply = (a, b) => a * b;
console.log(multiply(4, 2));
对象
对象以键‑值对的形式存储数据,并将状态与行为结合在一起。
const person = {
firstName: "John", // Property
lastName: "Doe", // Property
age: 50, // Property
fullName: function() { // Method
return this.firstName + " " + this.lastName;
}
};
console.log(person.fullName()); // "John Doe"
数组
JavaScript 中的数组用于在单个变量中存储多个值。
创建数组
let fruits = ["Apple", "Banana", "Orange"];
访问元素
console.log(fruits[0]); // Apple
console.log(fruits[2]); // Orange
长度
console.log(fruits.length); // 3
修改元素
fruits[1] = "Mango";
console.log(fruits); // ["Apple", "Mango", "Orange"]
常用数组方法
-
push()– 在末尾添加fruits.push("Grapes"); -
pop()– 从末尾移除fruits.pop(); -
unshift()– 在开头添加fruits.unshift("Pineapple"); -
shift()– 从开头移除fruits.shift();