javascript数组案例:JavaScript数组实战案例,DOM操作与数据过滤
在JavaScript开发中,数组是最常用的数据结构之一,本文将通过三个实用案例,展示如何在实际项目中灵活运用JavaScript数组方法,包括DOM操作、事件处理和数据过滤等场景。
动态生成导航菜单
<!DOCTYPE html>
<html>
<head>导航菜单示例</title>
<style>
.nav-item { display: inline-block; margin: 5px; padding: 10px; background: #f0f0f0; }
.nav-item:hover { background: #ddd; }
</style>
</head>
<body>
<div id="nav-menu"></div>
<script>
// 导航菜单数据
const menuItems = [
{ id: 1, text: "首页", href: "/" },
{ id: 2, text: "产品", href: "/products" },
{ id: 3, text: "服务", href: "/services" },
{ id: 4, text: "关于我们", href: "/about" },
{ id: 5, text: "联系我们", href: "/contact" }
];
// 获取容器元素
const navContainer = document.getElementById('nav-menu');
// 使用map方法生成菜单项
const navHTML = menuItems.map(item =>
`<a href="${item.href}" class="nav-item">${item.text}</a>`
).join('');
// 将生成的HTML插入到DOM中
navContainer.innerHTML = navHTML;
</script>
</body>
</html>
待办事项列表
<!DOCTYPE html>
<html>
<head>待办事项列表</title>
<style>
.todo-item { padding: 10px; border-bottom: 1px solid #eee; }
.completed { text-decoration: line-through; color: #888; }
</style>
</head>
<body>
<h1>待办事项</h1>
<form id="todo-form">
<input type="text" id="todo-input" placeholder="输入新任务...">
<button type="submit">添加</button>
</form>
<ul id="todo-list"></ul>
<script>
// 初始待办事项
let todos = [
{ id: 1, text: "学习JavaScript", completed: true },
{ id: 2, text: "完成项目", completed: false }
];
// 获取DOM元素
const todoForm = document.getElementById('todo-form');
const todoInput = document.getElementById('todo-input');
const todoList = document.getElementById('todo-list');
// 渲染待办事项列表
function renderTodos() {
// 清空现有列表
todoList.innerHTML = '';
// 使用filter方法过滤已完成的任务
const visibleTodos = todos.filter(todo => !todo.completed);
// 使用reduce方法计算未完成任务数量
const totalTodos = todos.reduce((count, todo) =>
todo.completed ? count : count + 1, 0);
// 更新页面标题显示任务数量
document.title = `待办事项 - ${totalTodos}个任务`;
// 使用map方法生成列表项
visibleTodos.forEach(todo => {
const li = document.createElement('li');
li.className = 'todo-item';
const checkbox = document.createElement('input');
checkbox.type = 'checkbox';
checkbox.checked = todo.completed;
checkbox.addEventListener('change', () => toggleComplete(todo.id));
const textSpan = document.createElement('span');
textSpan.textContent = todo.text;
const deleteBtn = document.createElement('button');
deleteBtn.textContent = '删除';
deleteBtn.addEventListener('click', () => deleteTodo(todo.id));
li.appendChild(checkbox);
li.appendChild(textSpan);
li.appendChild(deleteBtn);
todoList.appendChild(li);
});
}
// 切换任务完成状态
function toggleComplete(id) {
todos = todos.map(todo =>
todo.id === id ? { ...todo, completed: !todo.completed } : todo
);
renderTodos();
}
// 删除任务
function deleteTodo(id) {
todos = todos.filter(todo => todo.id !== id);
renderTodos();
}
// 表单提交事件处理
todoForm.addEventListener('submit', (e) => {
e.preventDefault();
const text = todoInput.value.trim();
if (text) {
const newId = todos.length > 0 ? Math.max(...todos.map(todo => todo.id)) + 1 : 1;
todos.push({ id: newId, text, completed: false });
todoInput.value = '';
renderTodos();
}
});
// 初始渲染
renderTodos();
</script>
</body>
</html>
数据过滤与搜索
<!DOCTYPE html>
<html>
<head>数据过滤示例</title>
<style>
.search-box { margin-bottom: 20px; }
.filtered-list { list-style: none; padding: 0; }
.filtered-list li { padding: 10px; border-bottom: 1px solid #eee; }
</style>
</head>
<body>
<h1>员工搜索</h1>
<div class="search-box">
<input type="text" id="search-input" placeholder="搜索员工...">
</div>
<ul id="employee-list" class="filtered-list"></ul>
<script>
// 员工数据
const employees = [
{ id: 1, name: "张三", department: "技术", salary: 15000 },
{ id: 2, name: "李四", department: "市场", salary: 12000 },
{ id: 3, name: "王五", department: "技术", salary: 18000 },
{ id: 4, name: "赵六", department: "人事", salary: 10000 },
{ id: 5, name: "钱七", department: "技术", salary: 20000 }
];
// 获取DOM元素
const searchInput = document.getElementById('search-input');
const employeeList = document.getElementById('employee-list');
// 渲染员工列表
function renderEmployees(searchTerm = '') {
// 使用filter方法根据搜索词过滤员工
const filteredEmployees = employees.filter(employee =>
employee.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
employee.department.toLowerCase().includes(searchTerm.toLowerCase())
);
// 使用map方法生成列表项
employeeList.innerHTML = filteredEmployees.map(employee =>
`<li>
<strong>${employee.name}</strong> - ${employee.department} - ¥${employee.salary.toLocaleString()}
</li>`
).join('');
}
// 搜索框事件监听
searchInput.addEventListener('input', () => {
renderEmployees(searchInput.value);
});
// 初始渲染
renderEmployees();
</script>
</body>
</html>
通过以上三个案例,我们可以看到JavaScript数组在实际开发中的多种应用:
- DOM操作:通过数组方法动态生成和更新页面内容
- 事件处理:结合数组实现交互式功能
- 数据过滤:使用数组方法实现搜索和筛选功能
掌握这些实用案例,将帮助您在实际项目中更高效地使用JavaScript数组,提升开发效率和代码质量。

文章已关闭评论!