JavaScript 是前端的编程语言,负责页面的交互逻辑。HTML 定义结构,CSS 定义样式,JavaScript 定义行为。它可以操作 DOM、发送网络请求、处理数据,是全栈开发的基础。
// let —— 可变变量(推荐)
let count = 0;
count = 1; // 允许重新赋值
// const —— 常量(推荐默认使用)
const PI = 3.14159;
// var —— 旧语法(不推荐)
var old = 'avoid';
// 基本类型
let str = 'hello'; // 字符串
let num = 42; // 数字
let bool = true; // 布尔
let empty = null; // 空值
let undef; // 未定义
// 引用类型
let arr = [1, 2, 3]; // 数组
let obj = { key: 'val' }; // 对象
let name = 'World';
let greeting = `Hello, ${name}!`; // 模板字符串
'hello'.toUpperCase(); // "HELLO"
'hello'.includes('ell'); // true
'hello'.slice(1, 3); // "el"
'a-b-c'.split('-'); // ['a', 'b', 'c']
['a', 'b'].join('-'); // "a-b"
' hello '.trim(); // "hello"
let nums = [1, 2, 3, 4, 5];
nums.forEach(n => console.log(n)); // 遍历
let doubled = nums.map(n => n * 2); // 映射
let evens = nums.filter(n => n % 2 === 0); // 过滤
let sum = nums.reduce((acc, n) => acc + n, 0); // 归约
let found = nums.find(n => n > 3); // 查找
nums.push(6); // 末尾添加
nums.pop(); // 末尾删除
nums.splice(1, 2); // 从索引1删2个
// 函数声明
function add(a, b) {
return a + b;
}
// 箭头函数(简洁写法)
const multiply = (a, b) => a * b;
// 默认参数
function greet(name = 'World') {
return `Hello, ${name}`;
}
// 剩余参数
function sum(...nums) {
return nums.reduce((a, b) => a + b, 0);
}
// 条件语句
let score = 85;
if (score >= 90) {
console.log('优秀');
} else if (score >= 80) {
console.log('良好');
} else {
console.log('继续努力');
}
// 三元表达式
let result = score >= 60 ? '通过' : '未通过';
// for...of(遍历数组)
for (let item of [10, 20, 30]) {
console.log(item);
}
// 数组解构
let [a, b, ...rest] = [1, 2, 3, 4];
// a=1, b=2, rest=[3,4]
// 对象解构
let { name, age, city = '未知' } = { name: 'Tom', age: 20 };
// name='Tom', age=20, city='未知'
本篇介绍了 JavaScript 的变量声明、数据类型、字符串与数组操作、函数定义、控制流语句和解构赋值。这些是 JS 编程的基石,务必熟练掌握。