一、JavaScript简介

JavaScript(简称JS) 是一门跨平台、面向对象的脚本语言,由浏览器直接解析执行,无需编译。
JavaScript能做什么?
| 改变页面内容 | 动态修改HTML元素的文字、样式 |
| 修改元素属性 | 改变图片src、链接href等属性值 |
| 表单验证 | 在用户提交前检查输入是否合法 |
| 响应用户操作 | 点击按钮、鼠标悬停等交互效果 |
| 定时任务 | 倒计时、轮播图等定时功能 |
JavaScript vs Java
虽然名字相似,但两者是完全不同的语言:
| 语言类型 | 脚本语言,解释执行 | 编译语言,需编译成字节码 |
| 运行环境 | 浏览器 | JVM虚拟机 |
| 用途 | 网页交互、前端开发 | 后端开发、Android开发 |
| 语法 | 弱类型,灵活 | 强类型,严谨 |
💡 JavaScript 于1995年由Brendan Eich发明,1997年成为ECMA标准。我们学习的是 ES6(ECMAScript 2015) 版本,是目前最主流的JS标准。
二、JavaScript引入方式
JS代码可以通过两种方式引入到HTML中:
2.1 内部脚本(内嵌式)
将JS代码写在HTML的<script>标签中:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>内部脚本示例</title>
</head>
<body>
<script>
alert("Hello JavaScript!");
</script>
</body>
</html>
特点:
- <script>标签可以放在HTML的任意位置(<head>或<body>中)
- 建议放在<body>底部,避免阻塞页面渲染
2.2 外部脚本(推荐)
将JS代码写在单独的.js文件中,通过src属性引入:
demo.js文件:
alert("Hello from external JS!");
HTML文件:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>外部脚本示例</title>
</head>
<body>
<script src="js/demo.js"></script>
</body>
</html>
注意:
- 外部JS文件中不能包含<script>标签
- <script>标签引入外部文件时不能自闭合,不能写成<script src="demo.js" />
- 外部脚本实现了结构与行为的分离,推荐在实际开发中使用
三、JavaScript基础语法
3.1 书写规范
// 1. 区分大小写
var name = "张三";
var Name = "李四"; // name 和 Name 是不同的变量
// 2. 每行结尾的分号可有可无(建议加上)
var age = 20;
var score = 90; // 分号使代码更清晰
// 3. 注释
// 这是单行注释
/* 这是
多行注释 */
// 4. 大括号表示代码块
if (age > 18) {
console.log("已成年");
}
3.2 输出语句
JS提供了三种输出方式:
| 警告框 | alert(内容) | 浏览器弹窗 |
| 页面写入 | document.write(内容) | HTML页面中 |
| 控制台 | console.log(内容) | 浏览器控制台(F12) |
// 警告框输出
alert("Hello JS!");
// 写入HTML页面
document.write("<h1>Hello World</h1>");
// 控制台输出(开发调试最常用)
console.log("调试信息");
console.log("变量值:", age);
3.3 变量
var关键字(ES5)
var name = "张三";
var age = 20;
// var的特点:
// 1. 作用域为全局(函数外定义的变量在代码块外也能访问)
{
var test = "hello";
}
console.log(test); // 可以访问,输出 "hello"
// 2. 允许重复定义
var age = 20;
var age = 30; // 不会报错,后面的值覆盖前面的
let关键字(ES6推荐)
let name = "张三";
let age = 20;
// let的特点:
// 1. 块级作用域,只在代码块内有效
{
let test = "hello";
}
console.log(test); // 报错:test is not defined
// 2. 不允许重复定义
let age = 20;
let age = 30; // 报错:Identifier 'age' has already been declared
const关键字(常量)
const PI = 3.14159;
const MAX_SIZE = 100;
// const的特点:
// 1. 声明时必须初始化
// 2. 声明后值不能修改
PI = 3.14; // 报错:Assignment to constant variable
💡 建议: 优先使用const,需要修改时用let,尽量不用var。
3.4 数据类型
JavaScript是弱类型语言,变量类型由赋的值决定。
| number | 数字(整数、小数、NaN) | 20, 99.8, NaN |
| string | 字符串(单双引号皆可) | "hello", 'world' |
| boolean | 布尔值 | true, false |
| null | 空对象 | null |
| undefined | 未初始化 | 变量声明未赋值时 |
| object | 对象(复杂类型) | {}, [] |
// 使用typeof查看数据类型
let age = 20;
console.log(typeof age); // "number"
let name = "张三";
console.log(typeof name); // "string"
let flag = true;
console.log(typeof flag); // "boolean"
let obj = null;
console.log(typeof obj); // "object"(JS的历史遗留问题)
let a;
console.log(typeof a); // "undefined"
⚠️ 注意: typeof null 返回"object",这是JavaScript最初实现时的错误,后来被ECMA标准沿用。
3.5 运算符
算术运算符
let a = 10, b = 3;
console.log(a + b); // 13
console.log(a – b); // 7
console.log(a * b); // 30
console.log(a / b); // 3.333…
console.log(a % b); // 1(取余)
console.log(a++); // 10(先使用,后自增)
console.log(++a); // 12(先自增,后使用)
关系运算符(重点:== vs ===)
let num1 = 20;
let num2 = "20";
// == :先进行类型转换,再比较值
console.log(num1 == num2); // true("20"转为数字20)
// === :先判断类型,类型不同直接返回false
console.log(num1 === num2); // false(number !== string)
| == | 判断值是否相等(会进行类型转换) |
| === | 判断值和类型是否都相等(推荐) |
| != | 判断值是否不相等 |
| !== | 判断值和类型是否都不相等 |
💡 建议: 开发中尽量使用===和!==,避免隐式类型转换带来的意外问题。
类型转换
// 字符串转数字
let str = "20";
let num1 = +str; // 使用正号运算符
let num2 = parseInt(str); // 使用parseInt函数(推荐)
let num3 = parseFloat("20.5"); // 转浮点数
// 布尔转数字
console.log(+true); // 1
console.log(+false); // 0
// 其他类型转布尔
console.log(Boolean(0)); // false
console.log(Boolean("")); // false
console.log(Boolean(null)); // false
console.log(Boolean(undefined)); // false
console.log(Boolean(NaN)); // false
// 其他所有值都转为true
3.6 流程控制语句
if语句
let score = 85;
if (score >= 90) {
console.log("优秀");
} else if (score >= 80) {
console.log("良好"); // 输出
} else if (score >= 60) {
console.log("及格");
} else {
console.log("不及格");
}
switch语句
let day = 3;
switch (day) {
case 1:
console.log("星期一");
break;
case 2:
console.log("星期二");
break;
case 3:
console.log("星期三"); // 输出
break;
default:
console.log("输入有误");
break;
}
循环语句
// for循环
let sum = 0;
for (let i = 1; i <= 100; i++) {
sum += i;
}
console.log(sum); // 5050
// while循环
let count = 0;
let i = 1;
while (i <= 100) {
count += i;
i++;
}
// do…while循环
let total = 0;
let j = 1;
do {
total += j;
j++;
} while (j <= 100);
3.7 函数
函数定义方式
// 方式1:function关键字定义
function add(a, b) {
return a + b;
}
// 方式2:函数表达式(匿名函数)
let multiply = function(a, b) {
return a * b;
};
// 方式3:箭头函数(ES6)
let divide = (a, b) => {
return a / b;
};
// 简写:如果只有一行return
let divide2 = (a, b) => a / b;
函数特点
// 1. 参数不需要声明类型
function greet(name) {
return "Hello, " + name;
}
// 2. 返回值不需要声明类型
function getMax(a, b) {
if (a > b) {
return a;
} else {
return b;
}
}
// 3. 可以传递任意个数参数
function sum() {
let total = 0;
for (let i = 0; i < arguments.length; i++) {
total += arguments[i];
}
return total;
}
console.log(sum(1, 2, 3, 4)); // 10
// 4. 函数调用
let result = add(10, 20);
console.log(result); // 30
四、JavaScript常用对象
4.1 Array数组对象
定义数组
// 方式1:使用new Array()
let arr1 = new Array(1, 2, 3);
// 方式2:使用字面量(推荐)
let arr2 = [1, 2, 3];
// 方式3:空数组
let arr3 = [];
数组特点
// 1. 长度可变
let arr = [1, 2, 3];
arr[10] = 10; // 自动扩容,中间索引为undefined
console.log(arr); // [1, 2, 3, empty × 7, 10]
console.log(arr[5]); // undefined
// 2. 可以存储任意类型
let mix = [1, "hello", true, null, {name: "张三"}];
// 3. 遍历数组
let nums = [10, 20, 30, 40];
for (let i = 0; i < nums.length; i++) {
console.log(nums[i]);
}
// ES6 for…of遍历
for (let num of nums) {
console.log(num);
}
常用方法
| push() | 末尾添加元素 | arr.push(4) |
| pop() | 删除末尾元素 | arr.pop() |
| shift() | 删除开头元素 | arr.shift() |
| unshift() | 开头添加元素 | arr.unshift(0) |
| splice() | 删除/添加元素 | arr.splice(1, 2, 'a') |
| sort() | 排序 | arr.sort() |
| reverse() | 反转 | arr.reverse() |
| join() | 转为字符串 | arr.join('-') |
| indexOf() | 查找索引 | arr.indexOf(2) |
| forEach() | 遍历 | arr.forEach(fn) |
| map() | 映射 | arr.map(fn) |
| filter() | 过滤 | arr.filter(fn) |
let fruits = ["apple", "banana", "orange"];
// 添加删除
fruits.push("grape"); // ["apple", "banana", "orange", "grape"]
fruits.pop(); // ["apple", "banana", "orange"]
// 排序和反转
let nums = [3, 1, 4, 1, 5];
nums.sort(); // [1, 1, 3, 4, 5]
nums.reverse(); // [5, 4, 3, 1, 1]
// 高级方法
let doubled = nums.map(n => n * 2); // [10, 8, 6, 2, 2]
let evens = nums.filter(n => n % 2 === 0); // [4, 2, 2]
let sum = nums.reduce((a, b) => a + b, 0); // 15
4.2 String字符串对象
let str = "Hello JavaScript";
// 常用属性
console.log(str.length); // 16
// 常用方法
console.log(str.charAt(0)); // "H"
console.log(str.indexOf("J")); // 6
console.log(str.substring(6, 10)); // "Java"
console.log(str.replace("Hello", "Hi")); // "Hi JavaScript"
console.log(str.split(" ")); // ["Hello", "JavaScript"]
console.log(str.toUpperCase()); // "HELLO JAVASCRIPT"
console.log(str.toLowerCase()); // "hello javascript"
console.log(str.trim()); // 去除两端空格
// 模板字符串(ES6)
let name = "张三";
let age = 25;
let info = `我叫${name},今年${age}岁`; // 我叫张三,今年25岁
4.3 自定义对象
// 方式1:对象字面量
let person = {
name: "张三",
age: 25,
sayHello: function() {
console.log("Hello, I'm " + this.name);
}
};
// 方式2:new Object()
let student = new Object();
student.name = "李四";
student.score = 90;
// 方式3:构造函数
function User(name, age) {
this.name = name;
this.age = age;
this.sayHi = function() {
console.log("Hi, " + this.name);
};
}
let user1 = new User("王五", 30);
user1.sayHi(); // Hi, 王五
// 访问属性
console.log(person.name); // 张三
console.log(person["age"]); // 25
// 遍历对象
for (let key in person) {
console.log(key + ": " + person[key]);
}
五、BOM浏览器对象模型
BOM(Browser Object Model)提供了与浏览器窗口交互的对象。
5.1 Window对象
Window是BOM的顶层对象,所有全局变量和函数都是Window的属性。
// window对象的方法可以省略window前缀
window.alert("hello"); // 等价于 alert("hello");
window.console.log("hi"); // 等价于 console.log("hi");
常用对话框
// 警告框
alert("这是一个警告框");
// 确认框(返回true/false)
let result = confirm("确定要删除吗?");
if (result) {
console.log("用户点击了确定");
} else {
console.log("用户点击了取消");
}
// 输入框(返回输入的内容或null)
let name = prompt("请输入您的姓名", "默认值");
console.log(name);
定时器
// setTimeout:延迟执行一次
let timer1 = setTimeout(() => {
console.log("3秒后执行");
}, 3000);
// 取消定时器
clearTimeout(timer1);
// setInterval:每隔一段时间执行一次
let count = 0;
let timer2 = setInterval(() => {
count++;
console.log("执行了第" + count + "次");
if (count >= 5) {
clearInterval(timer2); // 执行5次后停止
}
}, 1000); // 每隔1秒执行
打开/关闭窗口
// 打开新窗口
let newWindow = window.open("https://www.baidu.com", "_blank", "width=600,height=400");
// 关闭窗口
newWindow.close();
5.2 Location对象
用于操作浏览器的地址栏。
// 获取当前URL
console.log(location.href); // 完整URL
console.log(location.hostname); // 主机名
console.log(location.pathname); // 路径
console.log(location.port); // 端口号
console.log(location.protocol); // 协议
// 页面跳转(常用)
location.href = "https://www.baidu.com";
// 或
location.assign("https://www.baidu.com");
// 刷新页面
location.reload();
5.3 History对象
用于操作浏览器的历史记录。
// 后退一页
history.back();
// 前进一页
history.forward();
// 前进/后退n页
history.go(1); // 前进1页
history.go(–2); // 后退2页
六、DOM文档对象模型

DOM(Document Object Model)将HTML文档映射为一颗树形结构,每个HTML元素都是树中的一个节点,通过JS可以操作这些节点。
6.1 获取DOM元素
// 通过ID获取(唯一元素)
let element = document.getElementById("myId");
// 通过标签名获取(返回集合)
let elements = document.getElementsByTagName("div");
// 通过name属性获取(常用于表单元素)
let inputs = document.getElementsByName("username");
// 通过class名获取(返回集合)
let items = document.getElementsByClassName("item");
// CSS选择器获取(推荐,ES6)
let box = document.querySelector(".box"); // 获取第一个匹配的元素
let boxes = document.querySelectorAll(".box"); // 获取所有匹配的元素
6.2 操作DOM元素
let element = document.getElementById("myDiv");
// 修改内容
element.innerText = "新的文字内容"; // 纯文本
element.innerHTML = "<b>加粗文字</b>"; // 解析HTML标签
// 修改样式
element.style.color = "red";
element.style.fontSize = "20px"; // 注意:CSS属性名转为驼峰式
element.style.backgroundColor = "#f5f5f5";
// 修改属性
element.setAttribute("class", "new-class");
element.getAttribute("id");
element.removeAttribute("title");
// 直接操作属性(更常用)
element.className = "active";
element.id = "newId";
element.src = "new-image.jpg"; // 对img元素
6.3 创建和删除元素
// 创建新元素
let newDiv = document.createElement("div");
newDiv.innerText = "我是新创建的div";
newDiv.className = "new-box";
// 添加到页面
document.body.appendChild(newDiv);
// 在指定元素前插入
let target = document.getElementById("target");
document.body.insertBefore(newDiv, target);
// 删除元素
let oldDiv = document.getElementById("old");
oldDiv.parentNode.removeChild(oldDiv);
// 或(ES6)
oldDiv.remove();
七、事件监听
事件是用户与网页交互的触发机制,如点击、输入、鼠标移动等。
7.1 事件绑定方式
<!– 方式1:HTML属性绑定(不推荐) –>
<button onclick="handleClick()">点击我</button>
<!– 方式2:JS绑定(推荐) –>
<button id="btn">点击我</button>
<script>
let btn = document.getElementById("btn");
// 绑定点击事件
btn.onclick = function() {
console.log("按钮被点击了");
};
// 或 addEventListener(更灵活,可绑定多个事件)
btn.addEventListener("click", () => {
console.log("按钮被点击了");
});
</script>
7.2 常用事件
| onclick | 鼠标点击 |
| ondblclick | 鼠标双击 |
| onmouseover | 鼠标移入 |
| onmouseout | 鼠标移出 |
| onmousedown | 鼠标按下 |
| onmouseup | 鼠标抬起 |
| onfocus | 获得焦点 |
| onblur | 失去焦点 |
| onchange | 内容改变 |
| onkeydown | 键盘按下 |
| onkeyup | 键盘抬起 |
| onsubmit | 表单提交 |
| onload | 页面加载完成 |
| onresize | 窗口大小改变 |
7.3 事件示例:开关灯效果
<!DOCTYPE html>
<html>
<head>
<style>
body { transition: background-color 0.3s; }
.light-on { background-color: #fff; }
.light-off { background-color: #333; }
</style>
</head>
<body class="light-on">
<img id="light" src="images/off.gif" alt="灯泡">
<button id="onBtn">开灯</button>
<button id="offBtn">关灯</button>
<script>
let light = document.getElementById("light");
let onBtn = document.getElementById("onBtn");
let offBtn = document.getElementById("offBtn");
let body = document.body;
onBtn.onclick = function() {
light.src = "images/on.gif";
body.className = "light-on";
};
offBtn.onclick = function() {
light.src = "images/off.gif";
body.className = "light-off";
};
</script>
</body>
</html>
八、综合案例:表单验证
下面实现一个用户注册表单的实时验证功能:
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>用户注册</title>
<style>
.form-item { margin: 15px 0; }
.form-item label { display: inline-block; width: 100px; }
.form-item input { width: 200px; padding: 5px; }
.error { color: red; font-size: 12px; margin-left: 105px; }
.success { color: green; font-size: 12px; margin-left: 105px; }
.invalid { border: 1px solid red; }
.valid { border: 1px solid green; }
</style>
</head>
<body>
<h2>用户注册</h2>
<form id="regForm" onsubmit="return validateForm()">
<div class="form-item">
<label>用户名:</label>
<input type="text" id="username" placeholder="3-12位字母数字">
<div id="usernameMsg"></div>
</div>
<div class="form-item">
<label>密码:</label>
<input type="password" id="password" placeholder="6-16位">
<div id="passwordMsg"></div>
</div>
<div class="form-item">
<label>确认密码:</label>
<input type="password" id="confirmPwd" placeholder="再次输入密码">
<div id="confirmMsg"></div>
</div>
<div class="form-item">
<label>邮箱:</label>
<input type="text" id="email" placeholder="example@mail.com">
<div id="emailMsg"></div>
</div>
<div class="form-item">
<label></label>
<input type="submit" value="注册">
<input type="reset" value="重置">
</div>
</form>
<script>
// 获取元素
let username = document.getElementById("username");
let password = document.getElementById("password");
let confirmPwd = document.getElementById("confirmPwd");
let email = document.getElementById("email");
// 验证用户名
username.onblur = function() {
let value = username.value;
let msg = document.getElementById("usernameMsg");
if (value.length < 3 || value.length > 12) {
msg.className = "error";
msg.innerText = "用户名长度必须在3-12位之间";
username.className = "invalid";
} else if (!/^[a-zA-Z0-9]+$/.test(value)) {
msg.className = "error";
msg.innerText = "用户名只能包含字母和数字";
username.className = "invalid";
} else {
msg.className = "success";
msg.innerText = "用户名格式正确 ✓";
username.className = "valid";
}
};
// 验证密码
password.onblur = function() {
let value = password.value;
let msg = document.getElementById("passwordMsg");
if (value.length < 6 || value.length > 16) {
msg.className = "error";
msg.innerText = "密码长度必须在6-16位之间";
password.className = "invalid";
} else {
msg.className = "success";
msg.innerText = "密码格式正确 ✓";
password.className = "valid";
}
};
// 验证确认密码
confirmPwd.onblur = function() {
let msg = document.getElementById("confirmMsg");
if (confirmPwd.value !== password.value) {
msg.className = "error";
msg.innerText = "两次输入的密码不一致";
confirmPwd.className = "invalid";
} else if (confirmPwd.value === "") {
msg.className = "error";
msg.innerText = "请确认密码";
confirmPwd.className = "invalid";
} else {
msg.className = "success";
msg.innerText = "密码一致 ✓";
confirmPwd.className = "valid";
}
};
// 验证邮箱
email.onblur = function() {
let value = email.value;
let msg = document.getElementById("emailMsg");
let emailReg = /^[\\w-]+(\\.[\\w-]+)*@[\\w-]+(\\.[\\w-]+)+$/;
if (!emailReg.test(value)) {
msg.className = "error";
msg.innerText = "邮箱格式不正确";
email.className = "invalid";
} else {
msg.className = "success";
msg.innerText = "邮箱格式正确 ✓";
email.className = "valid";
}
};
// 表单提交验证
function validateForm() {
// 触发所有验证
username.onblur();
password.onblur();
confirmPwd.onblur();
email.onblur();
// 检查是否所有字段都有效
let inputs = document.querySelectorAll("input[type='text'], input[type='password']");
for (let input of inputs) {
if (input.className === "invalid" || input.value === "") {
alert("请正确填写所有信息!");
return false; // 阻止表单提交
}
}
return true; // 允许提交
}
</script>
</body>
</html>
本章小结
| JS简介 | 脚本语言,浏览器直接执行,实现网页交互 |
| 引入方式 | 内部<script>、外部src引入(推荐) |
| 变量 | var(全局)、let(块级)、const(常量) |
| 数据类型 | number、string、boolean、null、undefined、object |
| 运算符 | ===全等(推荐)、类型转换、+ – * / % |
| 流程控制 | if、switch、for、while、do…while |
| 函数 | function定义、箭头函数、参数任意个数 |
| 数组 | []定义、长度可变、类型不限、丰富的方法 |
| 字符串 | length、indexOf、substring、split、replace |
| 对象 | 字面量、new Object()、构造函数 |
| BOM | window、location、history |
| DOM | getElementById、querySelector、操作元素内容和样式 |
| 事件 | onclick、onblur、onchange、onsubmit等 |
| 正则 | test()、exec()、常用验证规则 |
如果本文对你有帮助,欢迎点赞 👍、收藏 ⭐、关注专栏!有问题欢迎在评论区交流讨论。




