JavaScript作为现代Web开发的基石语言,掌握其基础语法是每位开发者的必经之路。本文将系统性地介绍JavaScript的核心语法概念,帮助您构建坚实的编程基础。
JavaScript提供了三种变量声明方式:
// ES5
var name = "张三"; // 函数作用域
// ES6+
let age = 25; // 块级作用域
const PI = 3.14; // 块级作用域常量
最佳实践:
const
,需要重新赋值时改用let
var
,防止变量提升(hoisting)带来的问题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"
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)
10 == "10" // true (值相等)
10 === "10" // false (值和类型都相等)
10 != "10" // false
10 !== "10" // true
5 > 3 // true
5 <= 10 // true
true && false // false (AND)
true || false // true (OR)
!true // false (NOT)
// 短路求值
let result = true || console.log("不会执行");
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
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("未知");
}
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]);
}
function add(a, b) {
return a + b;
}
const multiply = function(a, b) {
return a * b;
};
const divide = (a, b) => a / b;
const square = x => x * x;
const log = () => console.log("Hello");
function greet(name = "Guest") {
console.log(`Hello, ${name}!`);
}
function sum(...numbers) {
return numbers.reduce((acc, num) => acc + num, 0);
}
const person = {
name: "李四",
age: 30,
greet() {
console.log(`你好,我是${this.name}`);
}
};
const fruits = ["苹果", "香蕉", "橙子"];
// 访问
fruits[0]; // "苹果"
// 修改
fruits[1] = "葡萄";
// 长度
fruits.length; // 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
// 数组解构
const [first, second] = ["苹果", "香蕉", "橙子"];
// 对象解构
const {name, age} = {name: "王五", age: 28};
// 参数解构
function printUser({name, age}) {
console.log(`${name}, ${age}岁`);
}
const greeting = `你好,${name}!
你今年${age}岁了。`;
const arr1 = [1, 2];
const arr2 = [3, 4];
const combined = [...arr1, ...arr2]; // [1, 2, 3, 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;
}
}
try {
// 可能出错的代码
nonExistentFunction();
} catch (error) {
console.error("出错:", error.message);
} finally {
console.log("无论如何都会执行");
}
function divide(a, b) {
if (b === 0) {
throw new Error("除数不能为零");
}
return a / b;
}
在脚本或函数开头添加:
"use strict";
// 严格模式下会报错的行为
x = 3.14; // 未声明变量
delete Object.prototype; // 删除不可删除属性
function fn(a, a) {} // 重复参数名
命名规则:
myVariable
)MAX_SIZE
)MyClass
)代码风格:
最佳实践:
掌握JavaScript基础语法是成为优秀开发者的第一步。本文涵盖了从变量声明到ES6+新特性的核心概念,建议读者通过实际编码练习来巩固这些知识。随着实践的深入,您会发现JavaScript虽然入门容易,但要精通仍需不断学习和积累经验。
记住:良好的编程习惯和扎实的基础知识比追求最新框架更重要。在后续学习中,您可以进一步探索异步编程、DOM操作、模块系统等更高级的主题。