ToolkitX
知识库工具箱

JavaScript 基础

变量、函数、对象、数组

20min·入门

01. 变量声明

JavaScript 有三种变量声明方式:var、let 和 const。let 和 const 是块作用域,推荐始终使用 const,需要修改时使用 let。
javascript
// const - 常量(推荐默认使用)
const API_URL = "https://api.example.com";

// let - 可变变量
let count = 0;
count = count + 1;

// 解构赋值
const [a, b, ...rest] = [1, 2, 3, 4, 5];
console.log(a, b, rest);  // 1 2 [3, 4, 5]

const { name, age } = { name: "Alice", age: 25 };

02. 函数

JavaScript 支持多种函数定义方式。箭头函数是 ES6 引入的简洁语法,没有自己的 this 绑定。
javascript
// 函数声明
function greet(name) {
return "Hello, " + name + "!";
}

// 箭头函数(推荐)
const add = (a, b) => a + b;
const double = x => x * 2;

// 默认参数
function createUser(name, role = "user") {
return { name, role };
}

// 剩余参数
function sum(...numbers) {
return numbers.reduce((total, n) => total + n, 0);
}

// 数组方法
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(n => n * 2);
const evens = numbers.filter(n => n % 2 === 0);
const total = numbers.reduce((sum, n) => sum + n, 0);

03. 对象与数组

对象是键值对的集合,数组是有序的元素列表。两者都支持现代的简写语法和操作方法。
javascript
// 对象简写
const name = "Alice";
const age = 25;
const user = { name, age };

// 对象展开
const defaults = { theme: "dark", lang: "zh" };
const config = { ...defaults, theme: "light" };

// 数组方法链式调用
const result = [1, 2, 3, 4, 5]
.filter(x => x % 2 === 0)
  .map(x => x * 10);

知识测验

1/5正确 0

let 和 const 的区别是什么?

下一节

DOM 操作

下一节