【JS-2】JavaScript基础语法完全指南:从入门到精通
JavaScript作为现代Web开发的基石语言,掌握其基础语法是每位开发者的必经之路。本文将系统性地介绍JavaScript的核心语法概念,帮助您构建坚实的编程基础。
1. 变量与数据类型
1.1 变量声明
JavaScript提供了三种变量声明方式:
// ES5
var name = "张三"; // 函数作用域// ES6+
let age = 25; // 块级作用域
const PI = 3.14; // 块级作用域常量
最佳实践:
- 默认使用
const
,需要重新赋值时改用let
- 避免使用
var
,防止变量提升(hoisting)带来的问题
1.2 数据类型
JavaScript是动态类型语言,包含7种原始类型和1种对象类型:
// 原始类型
let str = "字符串"; // String
let num = 123; // Number
let flag = true; // Boolean
let empty = null; // Null
let notDefined; // Undefined
let sym = Symbol("id"); // Symbol (ES6)
let bigInt = 9007199254740991n; // BigInt (ES2020)// 对象类型
let obj = { name: "对象" }; // Object
类型检测:
typeof "hello" // "string"
typeof 42 // "number"
typeof true // "boolean"
typeof {} // "object"
typeof [] // "object" (注意)
typeof null // "object" (历史遗留问题)
typeof Symbol() // "symbol"
2. 运算符与表达式
2.1 算术运算符
let sum = 10 + 5; // 15
let diff = 10 - 5; // 5
let product = 10 * 5; // 50
let quotient = 10 / 5; // 2
let remainder = 10 % 3; // 1
let exponent = 2 ** 3; // 8 (ES7)
2.2 比较运算符
10 == "10" // true (值相等)
10 === "10" // false (值和类型都相等)
10 != "10" // false
10 !== "10" // true
5 > 3 // true
5 <= 10 // true
2.3 逻辑运算符
true && false // false (AND)
true || false // true (OR)
!true // false (NOT)// 短路求值
let result = true || console.log("不会执行");
2.4 赋值运算符
let x = 10;
x += 5; // x = x + 5
x -= 3; // x = x - 3
x *= 2; // x = x * 2
x /= 4; // x = x / 4
x %= 3; // x = x % 3
3. 流程控制
3.1 条件语句
if…else
if (age < 18) {console.log("未成年");
} else if (age >= 18 && age < 60) {console.log("成年人");
} else {console.log("老年人");
}
三元运算符
let message = age >= 18 ? "成年人" : "未成年";
switch
switch (day) {case 1:console.log("周一");break;case 2:console.log("周二");break;// ...default:console.log("未知");
}
3.2 循环结构
for循环
for (let i = 0; i < 5; i++) {console.log(i);
}
while循环
let i = 0;
while (i < 5) {console.log(i);i++;
}
do…while
let j = 0;
do {console.log(j);j++;
} while (j < 5);
for…of (ES6)
const arr = [1, 2, 3];
for (const item of arr) {console.log(item);
}
for…in
const obj = {a: 1, b: 2};
for (const key in obj) {console.log(key, obj[key]);
}
4. 函数
4.1 函数声明
function add(a, b) {return a + b;
}
4.2 函数表达式
const multiply = function(a, b) {return a * b;
};
4.3 箭头函数 (ES6)
const divide = (a, b) => a / b;
const square = x => x * x;
const log = () => console.log("Hello");
4.4 默认参数 (ES6)
function greet(name = "Guest") {console.log(`Hello, ${name}!`);
}
4.5 剩余参数 (Rest Parameters)
function sum(...numbers) {return numbers.reduce((acc, num) => acc + num, 0);
}
5. 对象与数组
5.1 对象字面量
const person = {name: "李四",age: 30,greet() {console.log(`你好,我是${this.name}`);}
};
5.2 数组基础
const fruits = ["苹果", "香蕉", "橙子"];// 访问
fruits[0]; // "苹果"// 修改
fruits[1] = "葡萄";// 长度
fruits.length; // 3
5.3 常用数组方法
// 添加/删除
fruits.push("芒果"); // 末尾添加
fruits.pop(); // 删除最后一个
fruits.unshift("草莓"); // 开头添加
fruits.shift(); // 删除第一个// 遍历
fruits.forEach(fruit => console.log(fruit));// 映射
const lengths = fruits.map(fruit => fruit.length);// 过滤
const longFruits = fruits.filter(fruit => fruit.length > 2);// 查找
fruits.find(fruit => fruit === "苹果"); // "苹果"
fruits.includes("香蕉"); // true
6. ES6+新特性
6.1 解构赋值
// 数组解构
const [first, second] = ["苹果", "香蕉", "橙子"];// 对象解构
const {name, age} = {name: "王五", age: 28};// 参数解构
function printUser({name, age}) {console.log(`${name}, ${age}岁`);
}
6.2 模板字符串
const greeting = `你好,${name}!
你今年${age}岁了。`;
6.3 展开运算符
const arr1 = [1, 2];
const arr2 = [3, 4];
const combined = [...arr1, ...arr2]; // [1, 2, 3, 4]
6.4 类语法
class Person {constructor(name) {this.name = name;}greet() {console.log(`Hello, ${this.name}!`);}
}class Student extends Person {constructor(name, grade) {super(name);this.grade = grade;}
}
7. 错误处理
7.1 try…catch
try {// 可能出错的代码nonExistentFunction();
} catch (error) {console.error("出错:", error.message);
} finally {console.log("无论如何都会执行");
}
7.2 抛出错误
function divide(a, b) {if (b === 0) {throw new Error("除数不能为零");}return a / b;
}
8. 严格模式
在脚本或函数开头添加:
"use strict";// 严格模式下会报错的行为
x = 3.14; // 未声明变量
delete Object.prototype; // 删除不可删除属性
function fn(a, a) {} // 重复参数名
9. 编码规范建议
-
命名规则:
- 变量/函数:camelCase (
myVariable
) - 常量:UPPER_CASE (
MAX_SIZE
) - 类:PascalCase (
MyClass
)
- 变量/函数:camelCase (
-
代码风格:
- 使用2或4个空格缩进
- 语句结束加分号
- 大括号与语句同行
-
最佳实践:
- 避免全局变量
- 优先使用=而不是
- 使用const/let代替var
- 函数应该只做一件事
10. 结语
掌握JavaScript基础语法是成为优秀开发者的第一步。本文涵盖了从变量声明到ES6+新特性的核心概念,建议读者通过实际编码练习来巩固这些知识。随着实践的深入,您会发现JavaScript虽然入门容易,但要精通仍需不断学习和积累经验。
记住:良好的编程习惯和扎实的基础知识比追求最新框架更重要。在后续学习中,您可以进一步探索异步编程、DOM操作、模块系统等更高级的主题。