返回
利用代码片段精进你的 JavaScript 技能
前端
2023-11-07 06:37:59
在 JavaScript 的世界里,简短的代码通常意味着更高效的解决方案。本文将从项目开发和设计的角度,为你精选 16 个实用的 JavaScript 代码片段。
项目开发现场最需要
1. DOM 元素定位
// 根据元素 ID 定位
const element = document.getElementById('my-element');
// 根据元素类名定位
const elements = document.getElementsByClassName('my-class');
// 根据元素标签名定位
const elements = document.getElementsByTagName('p');
// 根据查询器定位元素
const element = document.querySelector('.my-class');
2. Cookie 管理
// 设置 cookie
document.cookie = 'myCookie=myValue';
// 获取 cookie
const cookieValue = document.cookie.split('; ').find(row => row.startsWith('myCookie=')).split('=')[1];
// 删除 cookie
document.cookie = 'myCookie=; expires=Thu, 01 Jan 1970 00:00:00 GMT';
3. 数组处理
// 创建数组
const numbers = [1, 2, 3, 4, 5];
// 数组长度
const length = numbers.length;
// 数组迭代
numbers.forEach((number, index) => {
console.log(`Index: ${index}, Number: ${number}`);
});
// 数组排序
numbers.sort((a, b) => a - b);
// 数组查找
const index = numbers.indexOf(3);
4. 对象操作
// 创建对象
const person = {
name: 'John Doe',
age: 30,
city: 'New York'
};
// 对象属性访问
const name = person.name;
// 对象属性设置
person.age = 31;
// 对象迭代
Object.keys(person).forEach(key => {
console.log(`Key: ${key}, Value: ${person[key]}`);
});
5. 函数应用
// 定义函数
function sum(a, b) {
return a + b;
}
// 函数调用
const result = sum(1, 2);
这些代码片段只是 JavaScript 知识海洋中的沧海一粟,它们可以帮助你解决项目开发中的各种常见问题,也能够激发你的创意,让你编写出更优雅、更高效的代码。