js基础功能实现
变量声明与数据类型
JavaScript 使用 var、let 或 const 声明变量:
var:函数作用域,可重复声明(不推荐使用)。let:块级作用域,不可重复声明。const:块级作用域,不可重复声明且不可重新赋值。
常见数据类型:
let num = 42; // Number
let str = "Hello"; // String
let bool = true; // Boolean
let obj = { key: 1 }; // Object
let arr = [1, 2, 3]; // Array
let nul = null; // Null
let undef; // Undefined
函数定义与调用
函数通过 function 关键字或箭头函数定义:
// 传统函数
function add(a, b) {
return a + b;
}
// 箭头函数
const multiply = (a, b) => a * b;
// 调用
console.log(add(2, 3)); // 输出 5
console.log(multiply(2, 3)); // 输出 6
条件与循环
条件语句使用 if...else 或 switch:

let score = 85;
if (score >= 90) {
console.log("A");
} else if (score >= 80) {
console.log("B");
} else {
console.log("C");
}
循环使用 for、while 或 forEach:
// for 循环
for (let i = 0; i < 5; i++) {
console.log(i);
}
// 数组遍历
const nums = [1, 2, 3];
nums.forEach(num => console.log(num));
事件处理
通过 addEventListener 绑定事件:
document.getElementById("myButton").addEventListener("click", () => {
alert("按钮被点击!");
});
DOM 操作
通过 JavaScript 操作 HTML 元素:

// 获取元素
const element = document.querySelector("#myDiv");
// 修改内容
element.textContent = "新文本";
// 修改样式
element.style.color = "red";
// 创建新元素
const newElement = document.createElement("p");
newElement.textContent = "动态添加的元素";
document.body.appendChild(newElement);
异步编程
使用 Promise 或 async/await 处理异步操作:
// Promise
fetch("https://api.example.com/data")
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
// async/await
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);
}
}
数组与对象方法
常用数组方法:
const numbers = [1, 2, 3];
numbers.push(4); // 添加元素
numbers.pop(); // 删除末尾元素
numbers.map(x => x * 2); // 返回新数组 [2, 4, 6]
numbers.filter(x => x > 1); // 返回 [2, 3]
对象操作:
const person = { name: "Alice", age: 25 };
console.log(person.name); // 访问属性
person.age = 26; // 修改属性
const keys = Object.keys(person); // 获取键名 ["name", "age"]






