JavaScript 入门教程
JavaScript 基础语法
JavaScript 是一种轻量级的脚本语言,通常用于网页开发。它可以直接嵌入 HTML 页面,由浏览器解释执行。以下是一个简单的 JavaScript 示例:
// 单行注释
/* 多行注释 */// 输出到控制台
console.log("Hello, World!");// 变量声明
let message = "Hello, JavaScript!";
const PI = 3.14159;
var oldWay = "Deprecated";
数据类型
JavaScript 是动态类型语言,变量可以保存任何类型的数据。基本数据类型包括:
// 数字
let age = 25;
let price = 99.99;// 字符串
let name = "Alice";
let greeting = 'Hello';// 布尔值
let isStudent = true;
let isWorking = false;// null 和 undefined
let empty = null;
let notDefined;// 对象
let person = {firstName: "John",lastName: "Doe",age: 30
};// 数组
let colors = ["red", "green", "blue"];
运算符
JavaScript 支持各种运算符:
// 算术运算符
let sum = 10 + 5; // 15
let difference = 10 - 5; // 5
let product = 10 * 5; // 50
let quotient = 10 / 5; // 2
let remainder = 10 % 3; // 1// 比较运算符
let isEqual = 10 == "10"; // true (值相等)
let isStrictEqual = 10 === "10"; // false (值和类型都相等)
let isNotEqual = 10 != "10"; // false
let isGreater = 10 > 5; // true// 逻辑运算符
let andResult = true && false; // false
let orResult = true || false; // true
let notResult = !true; // false
控制结构
JavaScript 提供了多种控制流程的方式:
// if 语句
let hour = 14;
if (hour < 12) {console.log("Good morning!");
} else if (hour < 18) {console.log("Good afternoon!");
} else {console.log("Good evening!");
}// switch 语句
let day = "Monday";
switch (day) {case "Monday":console.log("Start of work week");break;case "Friday":console.log("Weekend is coming");break;default:console.log("Midweek day");
}// for 循环
for (let i = 0; i < 5; i++) {console.log(i);
}// while 循环
let count = 0;
while (count < 3) {console.log(count);count++;
}// do-while 循环
let x = 0;
do {console.log(x);x++;
} while (x < 3);
函数
函数是 JavaScript 中的基本构建块:
// 函数定义
function greet(name) {return "Hello, " + name + "!";
}// 函数调用
let greeting = greet("Alice");
console.log(greeting); // 输出: Hello, Alice!// 箭头函数 (ES6)
const add = (a, b) => a + b;
console.log(add(2, 3)); // 5// 默认参数
function multiply(a, b = 1) {return a * b;
}
console.log(multiply(5)); // 5
console.log(multiply(5, 2)); // 10
DOM 操作
JavaScript 可以操作网页的文档对象模型(DOM):
// 获取元素
let heading = document.getElementById("main-heading");
let buttons = document.getElementsByClassName("btn");
let paragraphs = document.getElementsByTagName("p");// 修改内容
heading.textContent = "New Heading";// 修改样式
heading.style.color = "blue";
heading.style.fontSize = "24px";// 添加事件监听器
let button = document.getElementById("myButton");
button.addEventListener("click", function() {alert("Button clicked!");
});// 创建新元素
let newParagraph = document.createElement("p");
newParagraph.textContent = "This is a new paragraph.";
document.body.appendChild(newParagraph);
数组方法
JavaScript 提供了许多有用的数组方法:
let numbers = [1, 2, 3, 4, 5];// map: 对数组每个元素执行函数并返回新数组
let doubled = numbers.map(num => num * 2);
console.log(doubled); // [2, 4, 6, 8, 10]// filter: 过滤数组元素
let evens = numbers.filter(num => num % 2 === 0);
console.log(evens); // [2, 4]// reduce: 将数组缩减为单个值
let sum = numbers.reduce((total, num) => total + num, 0);
console.log(sum); // 15// forEach: 对每个元素执行函数
numbers.forEach(num => console.log(num));// find: 查找第一个满足条件的元素
let firstEven = numbers.find(num => num % 2 === 0);
console.log(firstEven); // 2
对象和类
JavaScript 支持面向对象编程:
// 对象字面量
let person = {firstName: "John",lastName: "Doe",age: 30,fullName: function() {return this.firstName + " " + this.lastName;}
};console.log(person.fullName()); // John Doe// 类 (ES6)
class Rectangle {constructor(width, height) {this.width = width;this.height = height;}area() {return this.width * this.height;}perimeter() {return 2 * (this.width + this.height);}
}let rect = new Rectangle(5, 10);
console.log(rect.area()); // 50
console.log(rect.perimeter()); // 30
错误处理
JavaScript 提供了错误处理机制:
try {// 可能出错的代码let result = dangerousOperation();console.log(result);
} catch (error) {// 处理错误console.error("An error occurred:", error.message);
} finally {// 无论是否出错都会执行的代码console.log("Operation attempted");
}function dangerousOperation() {throw new Error("Something went wrong");
}
异步编程
JavaScript 使用回调、Promise 和 async/await 处理异步操作:
// 回调函数
setTimeout(() => {console.log("This runs after 1 second");
}, 1000);// Promise
let promise = new Promise((resolve, reject) => {setTimeout(() => {resolve("Success!");}, 2000);
});promise.then(result => {console.log(result); // "Success!"
}).catch(error => {console.error(error);
});// async/await (ES8)
async function fetchData() {try {let response = await fetch('https://api.example.com/data');let data = await response.json();console.log(data);} catch (error) {console.error("Fetch error:", error);}
}fetchData();
ES6+ 新特性
现代 JavaScript 引入了许多新特性:
// 解构赋值
let [a, b] = [1, 2];
let {firstName, lastName} = {firstName: "John", lastName: "Doe"};// 扩展运算符
let arr1 = [1, 2, 3];
let arr2 = [...arr1, 4, 5]; // [1, 2, 3, 4, 5]// 模板字符串
let name = "Alice";
let greeting = `Hello, ${name}!`; // Hello, Alice!// 模块化
// math.js
export const PI = 3.14159;
export function square(x) { return x * x; }// app.js
import { PI, square } from './math.js';
console.log(square(PI));
最佳实践
编写高质量 JavaScript 代码的一些建议:
- 使用
const
和let
代替var
- 使用严格模式 (
'use strict';
) - 保持函数短小且单一职责
- 使用有意义的变量和函数名
- 避免全局变量
- 正确处理异步操作
- 编写可测试的代码
- 使用现代工具 (如 ESLint, Prettier)