js基础功能实现
变量声明与数据类型
JavaScript 使用 var、let 或 const 声明变量。let 和 const 是 ES6 新增的块级作用域声明方式,const 用于声明常量。
let name = "John"; // 字符串
const age = 25; // 数值
var isStudent = true; // 布尔值
JavaScript 是动态类型语言,常见数据类型包括:
- 原始类型:
String、Number、Boolean、null、undefined、Symbol(ES6) - 引用类型:
Object(包括Array、Function)
条件判断与循环
条件判断通过 if...else 或 switch 实现:
if (age >= 18) {
console.log("Adult");
} else {
console.log("Minor");
}
switch (day) {
case "Monday":
console.log("Start of week");
break;
default:
console.log("Other day");
}
循环常用 for、while 和 forEach(数组专用):
for (let i = 0; i < 5; i++) {
console.log(i);
}
let arr = [1, 2, 3];
arr.forEach(item => console.log(item));
函数定义与调用
函数可以通过声明式或表达式定义:
// 声明式
function greet(name) {
return `Hello, ${name}!`;
}
// 表达式(箭头函数)
const add = (a, b) => a + b;
调用函数时支持默认参数和剩余参数(ES6):
function log(message = "Default") {
console.log(message);
}
const sum = (...nums) => nums.reduce((acc, val) => acc + val, 0);
对象与数组操作
对象使用字面量或构造函数创建:
const person = {
name: "Alice",
sayHi() {
console.log(`Hi, I'm ${this.name}`);
}
};
// 动态属性名(ES6)
const key = "age";
person[key] = 30;
数组常用方法:
const numbers = [1, 2, 3];
numbers.push(4); // 末尾添加
numbers.pop(); // 末尾删除
numbers.map(x => x*2); // 映射新数组
numbers.filter(x => x > 1); // 过滤
DOM 操作基础
通过 document 对象访问和修改页面元素:
// 获取元素
const btn = document.getElementById("myButton");
const divs = document.querySelectorAll(".container");
// 事件监听
btn.addEventListener("click", () => {
divs[0].style.backgroundColor = "red";
});
// 动态创建元素
const newP = document.createElement("p");
newP.textContent = "New paragraph";
document.body.appendChild(newP);
异步编程
回调函数是传统异步处理方式:
setTimeout(() => console.log("Delayed"), 1000);
Promise(ES6)提供更清晰的链式调用:
fetch("https://api.example.com/data")
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
async/await(ES2017)进一步简化异步代码:
async function fetchData() {
try {
const response = await fetch("https://api.example.com/data");
const data = await response.json();
console.log(data);
} catch (error) {
console.error(error);
}
}
错误处理
使用 try...catch 捕获运行时错误:
try {
nonExistentFunction();
} catch (error) {
console.error("Error:", error.message);
} finally {
console.log("Execution completed");
}
模块化开发(ES6)
通过 export 和 import 实现模块化:

// math.js
export const PI = 3.14;
export function square(x) { return x * x; }
// app.js
import { PI, square } from './math.js';
console.log(square(PI));






