从基础到进阶,附带可运行演示示例
JavaScript 中有三种声明变量的方式:var(函数作用域)、let(块级作用域)、const(常量,块级作用域)。
let 和 const,避免使用 var。var a = 10; // 函数作用域 let b = 20; // 块级作用域 const PI = 3.14; // 常量,不可重新赋值 console.log(a, b, PI);
基本类型:Number、String、Boolean、Undefined、Null、Symbol、BigInt。引用类型:Object(含 Array、Function 等)。
console.log(typeof 42); // "number" console.log(typeof "hello"); // "string" console.log(typeof true); // "boolean" console.log(typeof { name: "JS" }); // "object"
算术、比较、逻辑、三元运算符等。
let x = 10, y = 3; console.log(x + y); // 13 console.log(x % y); // 1 console.log(x > y && y > 0); // true console.log(x > y ? "大" : "小"); // "大"
函数是 JavaScript 的一等公民,可以通过函数声明、函数表达式、箭头函数定义。
// 函数声明 function add(a, b) { return a + b; } // 箭头函数 const square = (n) => n * n; console.log(add(3, 5)); // 8 console.log(square(4)); // 16
常用方法:push、pop、map、filter、reduce 等。
const nums = [1, 2, 3, 4, 5]; const doubled = nums.map(n => n * 2); console.log(doubled); // [2,4,6,8,10] const evens = nums.filter(n => n % 2 === 0); console.log(evens); // [2,4] const sum = nums.reduce((a, b) => a + b, 0); console.log(sum); // 15
对象由键值对组成,支持属性访问、解构、展开运算符等。
const person = { name: "张三", age: 25, greet() { console.log(`你好,我是${this.name}`); } }; const { name, age } = person; // 解构 console.log(name, age); person.greet();
for、while、do...while、for...of、if...else 等控制结构。
for (let i = 1; i <= 5; i++) { if (i % 2 === 0) { console.log(i + " 是偶数"); } else { console.log(i + " 是奇数"); } }
模板字符串、解构赋值、展开运算符、Promise、async/await 等现代语法。
// 模板字符串 const name = "JS"; console.log(`Hello, ${name}!`); // 展开运算符 const arr1 = [1, 2]; const arr2 = [...arr1, 3, 4]; console.log(arr2); // Promise const p = new Promise((resolve) => resolve("异步成功") ); p.then(msg => console.log(msg));