JavaScript 基础语法教程
1. JavaScript简介
JavaScript是一种具有函数优先特性的轻量级、解释型或即时编译型的编程语言。它是最广泛使用的Web脚本语言,可以为网页添加交互性和动态功能。
2. 对象操作
2.1 对象的创建与基本操作
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| let user = { name: '张三', age: 18, sex: '男' };
user.address = "北京";
user["email"] = "zhangsan@example.com";
delete user.age;
|
2.2 对象的拷贝
1 2 3 4 5 6 7 8 9 10 11 12
| let teacher = {}; Object.assign(teacher, user);
let teacher1 = JSON.parse(JSON.stringify(user));
let teacher2 = Object.assign({}, user);
let teacher3 = teacher2;
|
2.3 属性访问
1 2 3 4 5 6 7 8 9 10 11 12 13
| let user = { name: '张三', age: 18 };
console.log(user.name);
console.log(user["name"]);
let { name, age } = user;
|
2.4 空值处理
1 2 3 4 5 6 7 8 9 10 11 12 13
| let a = null; let b = a?.x;
let d = null; let e = 1; let f = d ?? e;
let x = null; let y = 5; x ??= y;
|
3. 数组操作
3.1 数组的创建与基本操作
1 2 3 4 5 6 7 8 9 10 11 12
| let arr = new Array(); let arr1 = [1, 2, 3, 4, 5];
arr1.push(6); arr1.unshift(0);
arr1.pop(); arr1.shift(); arr1.splice(1, 2);
|
3.2 数组方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| let arr = [1, 2, 3, 4, 5]; let sliced = arr.slice(0, 2);
let arr1 = [1, 2]; let arr2 = [3, 4]; let combined = arr1.concat(arr2);
let str = "1,2,3,4,5"; let arr3 = str.split(",");
let arr4 = ["1", "2", "3"]; console.log(arr4.join(","));
|
3.3 数组高级操作
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| let numbers = [1, 10, 2, 20, 3]; numbers.sort((a, b) => a - b); numbers.sort((a, b) => b - a);
let users = [ { name: "张三", age: 18 }, { name: "李四", age: 19 } ]; let found = users.find(user => user.name === "张三"); let index = users.findIndex(user => user.name === "张三");
let filtered = users.filter(user => user.age > 18);
let names = users.map(user => user.name);
let sum = numbers.reduce((acc, cur) => acc + cur, 0);
|
4. JSON操作
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| let person = { "name": "张三", "age": 18, "address": { "city": "北京", "district": "朝阳" }, "hobbies": ["读书", "运动"] };
let jsonStr = '{"name": "张三", "age": 18}'; let obj = JSON.parse(jsonStr);
let str = JSON.stringify(person);
|
5. 注意事项
- 使用
===
而不是==
进行比较
- 避免使用全局变量
- 使用
const
和let
代替var
- 对象和数组的深浅拷贝要区分清楚
- 注意处理null和undefined值
6. 最佳实践
- 始终使用分号结束语句
- 使用驼峰命名法命名变量和函数
- 合理使用解构赋值
- 优先使用箭头函数
- 使用模板字符串代替字符串拼接
本文档涵盖了JavaScript的核心基础语法,掌握这些内容可以开始进行JavaScript开发。