JS中的函数、对象和数组

发布: (2025年12月25日 GMT+8 15:00)
2 min read
原文: Dev.to

Source: Dev.to

函数

函数是一段执行特定任务并且可以重复使用的代码块。JavaScript 中定义函数有三种方式:

  1. 函数声明
  2. 函数表达式
  3. 箭头函数(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();
Back to Blog

相关文章

阅读更多 »

函数与箭头函数

什么是函数?如果用简单的话来说,它们是 JavaScript 的主要构建块之一。它们用于将你的代码组织成小的模块……

JavaScript 中 Function 的核心前提

这算是 JavaScript 中的函数吗?javascript function fiveSquared { return 5 5; } 从技术上讲,是的。然而,fiveSquared 缺乏真实场景中所需的可复用性……