添加动态效果和用户交互功能
// var - 函数作用域,可重复声明
var name = "小明";
var name = "小红"; // 合法
// let - 块级作用域,不可重复声明
let age = 18;
// let age = 20; // 报错
// const - 常量,声明时必须赋值
const PI = 3.14159;
// PI = 3.14; // 报错
// 全局作用域
let globalVar = "我在任何地方都能访问";
function testScope() {
// 函数作用域
let functionVar = "我只能在函数内访问";
if (true) {
// 块级作用域
let blockVar = "我只能在if块内访问";
console.log(blockVar); // 正常
}
console.log(blockVar); // 报错
}
string - 字符串number - 数字boolean - 布尔值undefined - 未定义null - 空值symbol - 符号bigint - 大整数object - 对象array - 数组function - 函数date - 日期regexp - 正则typeof "hello" // "string"
typeof 123 // "number"
typeof true // "boolean"
typeof null // "object" (历史遗留问题)
typeof [] // "object"
Array.isArray([]) // true
+ 加法 5 + 3 = 8
- 减法 5 - 3 = 2
* 乘法 5 * 3 = 15
/ 除法 5 / 3 = 1.666...
% 取余 5 % 3 = 2
** 幂运算 5 ** 3 = 125
&& 逻辑与 true && false = false
|| 逻辑或 true || false = true
! 逻辑非 !true = false
?? 空值合并 null ?? "default" = "default"
?. 可选链 obj?.property?.value
// 简单if
if (score >= 60) {
console.log("及格了!");
}
// if-else
if (age >= 18) {
console.log("成年人");
} else {
console.log("未成年人");
}
// if-else if-else
if (score >= 90) {
grade = 'A';
} else if (score >= 80) {
grade = 'B';
} else if (score >= 70) {
grade = 'C';
} else {
grade = 'D';
}
switch (day) {
case 1:
console.log("星期一");
break;
case 2:
console.log("星期二");
break;
case 3:
case 4:
case 5:
console.log("工作日");
break;
default:
console.log("周末");
}
// for循环
for (let i = 0; i < 5; i++) {
console.log(i); // 0,1,2,3,4
}
// 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循环数组
const fruits = ['苹果', '香蕉', '橙子'];
for (const fruit of fruits) {
console.log(fruit);
}
// for...in循环对象
const person = {name: '小明', age: 18};
for (const key in person) {
console.log(key + ': ' + person[key]);
}
// forEach方法
fruits.forEach((fruit, index) => {
console.log(index + ': ' + fruit);
});
// 函数声明
function greet(name) {
return '你好,' + name;
}
// 函数表达式
const greet = function(name) {
return '你好,' + name;
};
// 构造函数
const greet = new Function('name', 'return "你好," + name');
// 箭头函数(简洁语法)
const greet = name => '你好,' + name;
// 箭头函数(完整语法)
const calculate = (a, b) => {
const sum = a + b;
return sum * 2;
};
// 默认参数
const greet = (name = '访客') => `你好,${name}`;
// 剩余参数
const sum = (...numbers) => {
return numbers.reduce((a, b) => a + b, 0);
};
const str = "Hello, JavaScript!";
// 长度和访问
str.length; // 18
str[0]; // "H"
str.charAt(1); // "e"
// 查找和替换
str.indexOf("Java"); // 7
str.includes("Script"); // true
str.replace("Hello", "Hi"); // "Hi, JavaScript!"
// 截取和分割
str.slice(0, 5); // "Hello"
str.substring(7, 13); // "JavaSc"
str.split(", "); // ["Hello", "JavaScript!"]
// 模板字符串
const name = "小明";
const greeting = `你好,${name}!今天学习${str.length}个字符。`;
// 大小写转换
"hello".toUpperCase(); // "HELLO"
"WORLD".toLowerCase(); // "world"
// 去除空白
" hello ".trim(); // "hello"
// 填充
"5".padStart(3, "0"); // "005"
"hello".padEnd(10, "!"); // "hello!!!!!"
// 检查开头和结尾
"JavaScript".startsWith("Java"); // true
"JavaScript".endsWith("Script"); // true
const fruits = ['苹果', '香蕉', '橙子'];
// 添加元素
fruits.push('葡萄'); // 末尾添加
fruits.unshift('草莓'); // 开头添加
// 删除元素
fruits.pop(); // 删除最后一个
fruits.shift(); // 删除第一个
// 查找元素
fruits.indexOf('香蕉'); // 1
fruits.includes('苹果'); // true
const numbers = [1, 2, 3, 4, 5];
// map - 映射
const doubled = numbers.map(n => n * 2);
// [2, 4, 6, 8, 10]
// filter - 过滤
const evens = numbers.filter(n => n % 2 === 0);
// [2, 4]
// reduce - 归约
const sum = numbers.reduce((a, b) => a + b, 0);
// 15
// find - 查找
const found = numbers.find(n => n > 3);
// 4
const students = [
{name: '小明', score: 85},
{name: '小红', score: 92},
{name: '小刚', score: 78}
];
// 按分数排序
students.sort((a, b) => b.score - a.score);
// 获取姓名列表
const names = students.map(s => s.name);
// ['小红', '小明', '小刚']
// 筛选高分学生
const highScores = students.filter(s => s.score >= 80);
// 对象字面量
const student = {
name: '小明',
age: 18,
grades: [85, 92, 78],
address: {
city: '北京',
district: '海淀区'
},
greet() {
return `你好,我是${this.name}`;
}
};
// 访问属性
student.name; // "小明"
student['age']; // 18
student.greet(); // "你好,我是小明"
// 添加/修改属性
student.email = 'xiaoming@example.com';
student.age = 19;
// 遍历对象
for (const key in student) {
console.log(key + ': ' + student[key]);
}
// 获取键/值/键值对
const keys = Object.keys(student);
const values = Object.values(student);
const entries = Object.entries(student);
// 对象解构
const {name, age, ...otherInfo} = student;
// 对象合并
const updatedStudent = {
...student,
hobby: '编程',
age: 20
};
// 创建Map
const scores = new Map();
scores.set('小明', 85);
scores.set('小红', 92);
scores.set('小刚', 78);
// Map操作
scores.get('小明'); // 85
scores.has('小红'); // true
scores.delete('小刚'); // true
scores.size; // 2
// 遍历Map
for (const [name, score] of scores) {
console.log(`${name}: ${score}分`);
}
// 创建Set
const uniqueNumbers = new Set([1, 2, 3, 2, 1]);
// Set {1, 2, 3}
// Set操作
uniqueNumbers.add(4); // Set {1, 2, 3, 4}
uniqueNumbers.has(2); // true
uniqueNumbers.delete(1); // true
uniqueNumbers.size; // 3
// 实际应用:数组去重
const numbers = [1, 2, 2, 3, 3, 4];
const unique = [...new Set(numbers)];
// [1, 2, 3, 4]
Math.PI; // 3.141592653589793
Math.round(4.7); // 5
Math.floor(4.7); // 4
Math.ceil(4.3); // 5
Math.random(); // 0-1之间的随机数
Math.max(1, 3, 5); // 5
Math.min(1, 3, 5); // 1
const now = new Date();
now.getFullYear(); // 2024
now.getMonth(); // 11 (0-11)
now.getDate(); // 19
now.getHours(); // 当前小时
now.getMinutes(); // 当前分钟
// 格式化日期
now.toLocaleDateString('zh-CN');
// "2024/12/19"
const student = {
name: "小明",
age: 18,
hobbies: ["编程", "阅读"]
};
// 对象转JSON字符串
const jsonString = JSON.stringify(student);
// "{"name":"小明","age":18,"hobbies":["编程","阅读"]}"
// JSON字符串转对象
const parsed = JSON.parse(jsonString);
// {name: "小明", age: 18, hobbies: ["编程", "阅读"]}
点击按钮改变背景颜色:
输入你的名字:
// 创建Promise
const fetchData = new Promise((resolve, reject) => {
setTimeout(() => {
const data = { name: '小明', age: 18 };
// 模拟成功
if (Math.random() > 0.3) {
resolve(data);
} else {
reject(new Error('网络错误'));
}
}, 1000);
});
// 使用Promise
fetchData
.then(data => {
console.log('获取数据:', data);
return data.name;
})
.then(name => {
console.log('姓名:', name);
})
.catch(error => {
console.error('错误:', error.message);
});
// Promise.all - 全部成功
const promises = [
Promise.resolve(1),
Promise.resolve(2),
Promise.resolve(3)
];
Promise.all(promises)
.then(results => {
console.log(results); // [1, 2, 3]
});
// Promise.race - 最快的一个
Promise.race([
new Promise(resolve => setTimeout(() => resolve('慢'), 1000)),
new Promise(resolve => setTimeout(() => resolve('快'), 500))
])
.then(result => {
console.log(result); // "快"
});
// 使用async/await改写Promise
async function getUserData(userId) {
try {
const response = await fetch(`/api/users/${userId}`);
const userData = await response.json();
// 等待多个异步操作
const [posts, comments] = await Promise.all([
fetch(`/api/posts?user=${userId}`).then(r => r.json()),
fetch(`/api/comments?user=${userId}`).then(r => r.json())
]);
return { userData, posts, comments };
} catch (error) {
console.error('获取用户数据失败:', error);
throw error;
}
}
// 使用async函数
getUserData(123)
.then(data => console.log(data))
.catch(error => console.error(error));
// 错误处理最佳实践
async function loadData() {
try {
// 设置超时
const timeout = new Promise((_, reject) =>
setTimeout(() => reject(new Error('请求超时')), 5000)
);
const data = await Promise.race([
fetchData(),
timeout
]);
return data;
} catch (error) {
if (error.message === '请求超时') {
showMessage('请求超时,请重试');
} else {
showMessage('获取数据失败');
}
throw error;
}
}
// GET请求
async function getPosts() {
const response = await fetch('https://jsonplaceholder.typicode.com/posts');
const posts = await response.json();
return posts;
}
// POST请求
async function createPost(postData) {
const response = await fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(postData)
});
return response.json();
}
// 存储数据
localStorage.setItem('username', '小明');
localStorage.setItem('settings', JSON.stringify({
theme: 'dark',
language: 'zh-CN'
}));
// 读取数据
const username = localStorage.getItem('username');
const settings = JSON.parse(localStorage.getItem('settings') || '{}');
// 删除数据
localStorage.removeItem('username');
localStorage.clear(); // 清空所有
// 定时器
const timer = setTimeout(() => {
console.log('1秒后执行');
}, 1000);
const interval = setInterval(() => {
console.log('每秒执行');
}, 1000);
clearTimeout(timer);
clearInterval(interval);
// 地理位置
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(
position => {
console.log('纬度:', position.coords.latitude);
console.log('经度:', position.coords.longitude);
},
error => console.error('获取位置失败:', error)
);
}
// 数组解构
const [first, second, ...rest] = [1, 2, 3, 4, 5];
console.log(first, second, rest); // 1 2 [3, 4, 5]
// 对象解构
const user = { name: '小明', age: 18, city: '北京' };
const { name, age, city = '上海' } = user;
// 函数参数解构
function greetUser({ name, age }) {
return `你好,${name}!你${age}岁了。`;
}
// 嵌套解构
const data = {
user: { name: '小红', scores: [85, 92, 78] }
};
const { user: { name: userName, scores: [firstScore] } } = data;
// 箭头函数
const add = (a, b) => a + b;
const greet = name => `你好,${name}!`;
const multiply = (x, y) => {
const result = x * y;
return result;
};
// 展开运算符
const arr1 = [1, 2, 3];
const arr2 = [...arr1, 4, 5]; // [1, 2, 3, 4, 5]
const obj1 = { a: 1, b: 2 };
const obj2 = { ...obj1, c: 3 }; // { a: 1, b: 2, c: 3 }
// 合并对象
const defaultSettings = { theme: 'light', lang: 'zh' };
const userSettings = { theme: 'dark' };
const finalSettings = { ...defaultSettings, ...userSettings };
小华是一名计算机系的大学生,每天有很多作业和项目要完成。 他需要一个工具来管理学习任务,避免遗漏重要事项。
class TodoApp {
constructor() {
this.todos = JSON.parse(localStorage.getItem('todos')) || [];
this.nextId = parseInt(localStorage.getItem('nextId')) || 1;
this.init();
}
addTodo(text, priority = 'medium') {
const todo = {
id: this.nextId++,
text: text,
completed: false,
priority: priority,
createdAt: new Date().toISOString()
};
this.todos.push(todo);
this.save();
this.render();
}
toggleTodo(id) {
const todo = this.todos.find(t => t.id === id);
if (todo) {
todo.completed = !todo.completed;
this.save();
this.render();
}
}
deleteTodo(id) {
this.todos = this.todos.filter(t => t.id !== id);
this.save();
this.render();
}
getStats() {
const total = this.todos.length;
const completed = this.todos.filter(t => t.completed).length;
const pending = total - completed;
return { total, completed, pending };
}
}
小美计划周末出游,需要查询各地天气情况。 她希望有一个简单的天气查询工具,可以输入城市名称获取天气信息。
class WeatherApp {
constructor(apiKey) {
this.apiKey = apiKey;
this.init();
}
async getWeather(city) {
try {
const url = `https://api.openweathermap.org/data/2.5/weather?q=\${city}&appid=\${this.apiKey}&units=metric&lang=zh_cn`;
const response = await fetch(url);
if (!response.ok) {
throw new Error('城市未找到');
}
const data = await response.json();
return {
city: data.name,
temperature: data.main.temp,
description: data.weather[0].description,
humidity: data.main.humidity,
windSpeed: data.wind.speed
};
} catch (error) {
console.error('获取天气失败:', error);
throw error;
}
}
displayWeather(weatherData) {
const weatherDiv = document.getElementById('weather-display');
weatherDiv.innerHTML = \`
\${weatherData.city}
温度: \${weatherData.temperature}°C
天气: \${weatherData.description}
湿度: \${weatherData.humidity}%
风速: \${weatherData.windSpeed} m/s
\`;
}
}
小强是一名数学系学生,需要一个功能完整的计算器来做作业。 他希望计算器支持基本的四则运算,还能处理小数和负数。
class Calculator {
constructor() {
this.currentInput = '0';
this.previousInput = '';
this.operator = null;
this.shouldResetScreen = false;
this.init();
}
appendNumber(number) {
if (this.shouldResetScreen) {
this.currentInput = '';
this.shouldResetScreen = false;
}
if (this.currentInput === '0') {
this.currentInput = number;
} else {
this.currentInput += number;
}
this.updateDisplay();
}
chooseOperator(operator) {
if (this.operator !== null) this.calculate();
this.previousInput = this.currentInput;
this.operator = operator;
this.shouldResetScreen = true;
}
calculate() {
const prev = parseFloat(this.previousInput);
const current = parseFloat(this.currentInput);
if (isNaN(prev) || isNaN(current)) return;
let result;
switch (this.operator) {
case '+': result = prev + current; break;
case '-': result = prev - current; break;
case '*': result = prev * current; break;
case '/': result = prev / current; break;
default: return;
}
this.currentInput = result.toString();
this.operator = null;
this.shouldResetScreen = true;
this.updateDisplay();
}
updateDisplay() {
document.getElementById('display').textContent = this.currentInput;
}
}
小丽开了一家网店,需要一个购物车系统。 她希望客户可以添加商品、修改数量、计算总价。
class ShoppingCart {
constructor() {
this.items = [];
this.init();
}
addItem(product) {
const existingItem = this.items.find(item => item.id === product.id);
if (existingItem) {
existingItem.quantity += 1;
} else {
this.items.push({...product, quantity: 1});
}
this.updateCart();
}
removeItem(productId) {
this.items = this.items.filter(item => item.id !== productId);
this.updateCart();
}
updateQuantity(productId, newQuantity) {
const item = this.items.find(item => item.id === productId);
if (item) {
item.quantity = Math.max(0, newQuantity);
if (item.quantity === 0) {
this.removeItem(productId);
} else {
this.updateCart();
}
}
}
getTotal() {
return this.items.reduce((total, item) => {
return total + (item.price * item.quantity);
}, 0);
}
getItemCount() {
return this.items.reduce((count, item) => count + item.quantity, 0);
}
}
将摄氏度转换为华氏度
function celsiusToFahrenheit(c) {
return c * 9/5 + 32;
}
// 测试
console.log(celsiusToFahrenheit(0)); // 32
console.log(celsiusToFahrenheit(100)); // 212
创建包含姓名、年龄、邮箱的对象
const person = {
name: "张三",
age: 25,
email: "zhangsan@example.com",
greet() {
return `你好,我是${this.name},今年${this.age}岁`;
}
};
console.log(person.greet());
判断变量类型的函数
function getType(value) {
if (value === null) return 'null';
if (Array.isArray(value)) return 'array';
return typeof value;
}
// 测试
console.log(getType(123)); // 'number'
console.log(getType([1,2,3])); // 'array'
根据分数返回等级
function getGrade(score) {
if (score >= 90) return '优秀';
else if (score >= 80) return '良好';
else if (score >= 70) return '中等';
else if (score >= 60) return '及格';
else return '不及格';
}
// 测试
console.log(getGrade(85)); // '良好'
判断某年是否为闰年
function isLeapYear(year) {
return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
}
// 测试
console.log(isLeapYear(2024)); // true
console.log(isLeapYear(2023)); // false
根据购买金额计算折扣
function calculateDiscount(amount) {
let discount = 0;
if (amount >= 500) discount = 0.2;
else if (amount >= 300) discount = 0.1;
else if (amount >= 100) discount = 0.05;
return {
original: amount,
discount: amount * discount,
final: amount * (1 - discount)
};
}
// 测试
console.log(calculateDiscount(400));
打印九九乘法表
function printMultiplicationTable() {
let table = '';
for (let i = 1; i <= 9; i++) {
let row = '';
for (let j = 1; j <= i; j++) {
row += `${j}×${i}=${i*j}\t`;
}
table += row + '\n';
}
return table;
}
console.log(printMultiplicationTable());
计算数组元素的总和
function sumArray(arr) {
let sum = 0;
for (let num of arr) {
sum += num;
}
return sum;
}
function sumArrayReduce(arr) {
return arr.reduce((sum, num) => sum + num, 0);
}
// 测试
console.log(sumArray([1, 2, 3, 4, 5])); // 15
找出数组中的最大值
function findMax(arr) {
let max = arr[0];
for (let i = 1; i < arr.length; i++) {
if (arr[i] > max) max = arr[i];
}
return max;
}
function findMaxMath(arr) {
return Math.max(...arr);
}
// 测试
console.log(findMax([3, 7, 2, 9, 1])); // 9
计算数字的阶乘
function factorial(n) {
if (n < 0) return undefined;
if (n <= 1) return 1;
return n * factorial(n - 1);
}
// 迭代版本
function factorialIterative(n) {
let result = 1;
for (let i = 2; i <= n; i++) {
result *= i;
}
return result;
}
// 测试
console.log(factorial(5)); // 120
生成前n个斐波那契数
function fibonacci(n) {
if (n <= 0) return [];
if (n === 1) return [0];
if (n === 2) return [0, 1];
const fib = [0, 1];
for (let i = 2; i < n; i++) {
fib[i] = fib[i - 1] + fib[i - 2];
}
return fib;
}
// 测试
console.log(fibonacci(10));
反转字符串
function reverseString(str) {
return str.split('').reverse().join('');
}
// 多种方法
function reverseString2(str) {
let reversed = '';
for (let char of str) {
reversed = char + reversed;
}
return reversed;
}
// 测试
console.log(reverseString("hello")); // "olleh"
使用API获取实时天气
完整的任务管理系统
功能完整的计算器
富文本编辑器
HTML5 Canvas绘图
网页音乐播放器
数字和模拟时钟
事件倒计时
图片展示和管理
颜色工具
安全密码生成
各种单位转换
生成二维码
文件操作界面
实时聊天界面
let a = 5, b = 10;
[a, b] = [b, a]; // ES6解构赋值
console.log(a, b); // 10 5
const random = Math.floor(Math.random() * 100) + 1;
console.log(`随机数: ${random}`);
const arr = [1, 2, 2, 3, 3, 4];
const unique = [...new Set(arr)];
console.log(unique); // [1, 2, 3, 4]
const name = "小明";
const age = 18;
console.log(`你好,${name},今年${age}岁`);