一些前端优质的代码片段

在前端编程中,高质量的代码不仅实现功能,还注重可读性、可维护性和性能。以下是一些值得品味和学习的优质前端代码片段,涵盖了函数式编程、ES6新特性、以及一些最佳实践示例:

文章目录

  • 1. 箭头函数与数组方法结合使用
  • 2. 解构赋值
  • 3. 模板字符串
  • 4. 使用Set去重
  • 5. Promise链式调用
  • 6. 立即执行函数表达式(IIFE)用于模块化
  • 7. 使用默认参数和Rest参数
  • 8.时间函数 - 格式化日期
  • 9.文件上传 - 预览图片
  • 10.单行与多行文本省略
      • 单行与多行文本省略
      • 多行文本省略
  • 11.动画效果 - 使用requestAnimationFrame实现平滑滚动
  • 12.DOM操作 - 动态创建与插入元素
  • 13.异步- async/await处理异步操作
  • 14.ES6解构与展开运算符 - 快速交换变量值
  • 15.Promise.allSettled 与并发请求管理
  • 16.使用 async/await 和 try/catch 进行错误处理
  • 17.生成器函数与迭代协议
  • 18.使用Map和Set进行高效数据操作
  • 19.防抖(debounce)函数 - 减少高频触发的函数调用
  • 20.限制并发
  • 21.解构赋值与默认值结合
  • 22.扁平化数组与映射
  • 23.使用Proxy进行对象属性访问的监控
  • 24.利用Symbol实现私有属性
  • 25.利用async iterators处理异步流
  • 26.使用CSS Custom Properties(变量)进行主题切换

1. 箭头函数与数组方法结合使用

const numbers = [1, 2, 3, 4, 5];
const squared = numbers.map(number => number * number);
console.log(squared); // 输出: [1, 4, 9, 16, 25]

这段代码展示了如何使用箭头函数和map方法简洁地对数组元素进行操作。

2. 解构赋值

const user = { firstName: 'John', lastName: 'Doe' };
const { firstName, lastName } = user;
console.log(`${firstName} ${lastName}`); // 输出: John Doe

解构赋值使得从对象或数组中提取值变得非常直观和简洁。

3. 模板字符串

const name = 'Alice';
const greeting = `Hello, ${name}! Welcome to our website.`;
console.log(greeting); // 输出: Hello, Alice! Welcome to our website.

模板字符串提供了一种更自然的方式来插入变量和表达式到字符串中,增强了代码的可读性。

4. 使用Set去重

const array = [1, 2, 2, 3, 4, 4, 5];
const uniqueArray = [...new Set(array)];
console.log(uniqueArray); // 输出: [1, 2, 3, 4, 5]

利用Set数据结构的唯一性,可以优雅地去除数组中的重复元素。

5. Promise链式调用

fetch('https://api.example.com/data').then(response => response.json()).then(data => console.log(data)).catch(error => console.error('Error:', error));

展示了如何使用Promise来处理异步操作,保持代码结构清晰,易于理解和维护。

6. 立即执行函数表达式(IIFE)用于模块化

(function() {const privateVar = 'I am private';window.myModule = {publicMethod: function() {console.log(privateVar);}};
})();
myModule.publicMethod(); // 输出: I am private

IIFE用来创建作用域,避免全局污染,是早期JavaScript中实现模块化的一种方式。

7. 使用默认参数和Rest参数

function greet(name = 'Guest', ...greetings) {greetings.forEach(greeting => console.log(`${greeting}, ${name}!`));
}greet('Alice', 'Hello', 'Welcome'); 
// 输出:
// Hello, Alice!
// Welcome, Alice!

默认参数使得函数调用更加灵活,而Rest参数允许你将不确定数量的参数作为一个数组传入。

8.时间函数 - 格式化日期

function formatDate(date) {const options = { year: 'numeric', month: 'long', day: 'numeric' };return new Date(date).toLocaleDateString('zh-CN', options);
}
console.log(formatDate(new Date())); // 输出:如 "2023年4月16日"

9.文件上传 - 预览图片

<input type="file" id="imageFile" accept="image/*" />
<img id="preview" src="#" alt="Image preview" style="display:none;" /><script>
document.getElementById('imageFile').addEventListener('change', (e) => {const file = e.target.files[0];if (file) {const reader = new FileReader();reader.onload = (event) => {document.getElementById('preview').src = event.target.result;document.getElementById('preview').style.display = 'block';};reader.readAsDataURL(file);}
});
</script>

10.单行与多行文本省略

单行与多行文本省略

<p class="single-line-ellipsis">这是一个很长很长的句子,可能会超出容器的宽度。</p>
.single-line-ellipsis {width: 200px;white-space: nowrap;overflow: hidden;text-overflow: ellipsis;
}

多行文本省略

<p class="multi-line-ellipsis">这里是一个多行文本的例子,它将会在超过指定行数后被省略显示,以保持界面的整洁。</p>
.multi-line-ellipsis {display: -webkit-box;-webkit-line-clamp: 3; /* 显示行数 */-webkit-box-orient: vertical;  overflow: hidden;
}

11.动画效果 - 使用requestAnimationFrame实现平滑滚动

function smoothScroll(target, duration) {const start = window.pageYOffset;const distance = target.getBoundingClientRect().top;const startTime = performance.now();function step(currentTime) {const timeElapsed = currentTime - startTime;const progress = Math.min(timeElapsed / duration, 1);window.scrollTo(0, start + distance * progress);if (timeElapsed < duration) {requestAnimationFrame(step);}}requestAnimationFrame(step);
}// 使用方法:平滑滚动到页面顶部
smoothScroll(document.documentElement, 1000);

12.DOM操作 - 动态创建与插入元素

function createElementWithText(tag, text) {const element = document.createElement(tag);element.textContent = text;return element;
}const div = createElementWithText('div', '新创建的Div元素');
document.body.appendChild(div);

13.异步- async/await处理异步操作

async function fetchUserData(userId) {try {const response = await fetch(`https://api.example.com/users/${userId}`);if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);const userData = await response.json();console.log(userData);} catch (error) {console.error('There was a problem with the fetch operation:', error);}
}fetchUserData(123);

14.ES6解构与展开运算符 - 快速交换变量值

let a = 1;
let b = 2;[a, b] = [b, a];
console.log(a, b); // 输出: 2 1

15.Promise.allSettled 与并发请求管理

使用 Promise.allSettled 处理多个异步操作,无论这些操作成功还是失败,都能获取到每个操作的结果。

async function fetchResources(urls) {const promises = urls.map(url =>fetch(url).then(response => ({status: 'fulfilled',value: response})).catch(error => ({status: 'rejected',reason: error})));return Promise.allSettled(promises);
}const urls = ['https://api.example.com/data1', 'https://api.example.com/data2'];
fetchResources(urls).then(results => {results.forEach((result, index) => {if (result.status === 'fulfilled') {console.log(`Resource ${index + 1} fetched successfully.`);} else {console.error(`Failed to fetch resource ${index + 1}:`, result.reason);}});
});

16.使用 async/await 和 try/catch 进行错误处理

优雅地处理异步操作中的错误,提高代码可读性。

async function fetchData(id) {try {const response = await fetch(`https://api.example.com/items/${id}`);if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);const data = await response.json();console.log(data);} catch(error) {console.error('There was a problem fetching the data:', error);}
}fetchData(123)

17.生成器函数与迭代协议

function* fibonacci() {let prev = 0, curr = 1;while (true) {[prev, curr] = [curr, prev + curr];yield curr;}
}const fibGen = fibonacci();console.log(fibGen.next().value); // 1
console.log(fibGen.next().value); // 1
console.log(fibGen.next().value); // 2

18.使用Map和Set进行高效数据操作

利用ES6MapSet数据结构来解决特定问题,提高代码效率。

const map = new Map();
map.set('apple', 1);
map.set('banana', 2);
console.log(map.get('apple')); // 输出: 1const set = new Set([1, 2, 3, 9, 5, 2]);
console.log([...new Set([...set].filter(x => x % 2 === 0))]); // 输出去重后的偶数集合: [2, 4]

19.防抖(debounce)函数 - 减少高频触发的函数调用

function debounce(func, wait) {let timeout;return function(...args) {clearTimeout(timeout);timeout = setTimeout(() => func.apply(this, args), wait);};
}const handleResize = debounce(function() {console.log('窗口大小已调整');
}, 300);window.addEventListener('resize', handleResize);

20.限制并发

/*** 异步并发控制函数* * @param {number} poolLimit - 并发执行的最大任务数量* @param {Iterable<any>} iterable - 包含待执行任务输入的可迭代对象* @param {(item: any, index: number) => Promise<any>} iteratorFn - 异步任务处理器,接收迭代对象的元素和其索引为参数* @returns {Promise<any[]>} - 所有异步任务完成后的结果数组*/
async function asyncPool(poolLimit, iterable, iteratorFn) {// 结果数组,用于收集所有异步任务的完成结果const results = [];// 正在执行的任务集合,使用Set以便快速查找和删除const executing = new Set();// 遍历可迭代对象for (const [index, item] of iterable.entries()) {// 构建异步任务Promise,并立即执行const taskPromise = (async () => {try {// 执行异步任务并等待结果const result = await iteratorFn(item, index);results[index] = result; // 根据索引位置填充结果数组} finally {// 无论任务成功还是失败,都要从执行集合中移除executing.delete(taskPromise);}})();// 添加到执行集合executing.add(taskPromise);// 控制并发数量,当达到限制时等待任何一个任务完成if (executing.size >= poolLimit) {await Promise.race(executing);}}// 确保所有任务(即使在循环结束时尚未启动的)都完成await Promise.all(executing);return results;
}// 示例使用
(async () => {// 模拟异步任务函数,参数i模拟不同的延迟时间const delayAsync = (i) => new Promise(resolve => setTimeout(() => resolve(`Task ${i} done after ${i}ms`), i));// 调用asyncPool控制并发执行const results = await asyncPool(2, [1000, 2000, 500, 1500], delayAsync);console.log(results);
})();

21.解构赋值与默认值结合

function welcomeUser({ name = 'Guest', role = 'Visitor' }) {console.log(`Welcome, ${name} (${role})!`);
}welcomeUser({ name: 'Alice' }); // 输出: Welcome, Alice (Visitor)!
welcomeUser({}); // 输出: Welcome, Guest (Visitor)!

22.扁平化数组与映射

const nestedArray = [[1, 2], [3, 4], [5]];
const flatMappedArray = nestedArray.flat().map(item => item * 2);
console.log(flatMappedArray); // 输出: [2, 4, 6, 8, 10]

23.使用Proxy进行对象属性访问的监控

const person = { name: 'Alice', age: 30 };
const personProxy = new Proxy(person, {get(target, prop) {console.log(`Accessing property: ${prop}`);return target[prop];},set(target, prop, value) {console.log(`Setting property ${prop} to ${value}`);target[prop] = value;return true;}
});personProxy.name; // 输出: Accessing property: name
personProxy.age = 31; // 输出: Setting property age to 31

24.利用Symbol实现私有属性

const _secret = Symbol('secret');class SecretHolder {constructor(secret) {this[_secret] = secret;}revealSecret() {return this[_secret];}
}const instance = new SecretHolder('classified information');
console.log(instance.revealSecret()); // 输出: classified information
// 注意:直接访问_secret属性是不可见的,保护了私有性

25.利用async iterators处理异步流

async function* generateNumbers(limit) {for (let i = 1; i <= limit; i++) {await new Promise(resolve => setTimeout(resolve, 1000)); // 模拟异步yield i;}
}(async () => {for await (const num of generateNumbers(5)) {console.log(num);}
})();
// 每秒输出一个数字,从1到5

26.使用CSS Custom Properties(变量)进行主题切换

CSS变量不仅简化了样式管理,还便于实现动态主题切换功能。

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Theme Switcher</title>
<style>:root {--primary-color: #3f51b5;--secondary-color: #f50057;--text-color: #ffffff;}body {color: var(--text-color);background: var(--primary-color);}.button {background-color: var(--secondary-color);color: var(--text-color);border-radius: 4px;padding: 10px 20px;transition: background-color 0.3s ease;}.button:hover {background-color: darken(var(--secondary-color), 10%);}/* 假设有一个按钮用于切换主题 */.toggle-button {cursor: pointer;}/* 主题切换示例 */.dark-theme {--primary-color: #212121;--secondary-color: #9c27b0;}
</style>
</head>
<body>
<button class="button toggle-button">Toggle Dark Theme</button>
<script>// 这里需要JavaScript来实际切换主题类document.querySelector('.toggle-button').addEventListener('click', function() {document.body.classList.toggle('dark-theme');});
</script>
</body>
</html>

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/853754.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Digital电路仿真软件的安装

文章目录 1. Java环境的安装 2. Digital安装 3. 软件配置 1. Java环境的安装 电路仿真软件Digital是一款用于设计和仿真数字逻辑电路的工具。它可以帮助用户创建、测试和调试各种数字电路&#xff0c;提供可视化的电路编辑环境&#xff0c;使得设计过程更加直观和便捷。 D…

MySQL数据操作与查询- 连接查询

一、引入 1、为什么需要使用连接查询&#xff1f; 查询信息的来源如果来自多张表&#xff0c;则必须对这些表进行连接查询。 2、连接查询的分类 内连接和外连接。 二、内连接 1、概述 将两张表的记录组合在一起&#xff0c;产生一个新的结果。 &#xff08;1&#xff09…

【Java】过滤器/拦截器

文章目录 两者区别request链路全过程 在实际开发中&#xff0c;过滤器和拦截器都是经常使用的技术&#xff0c;但一被提及到其区别时&#xff0c;整个人就愣住了&#xff0c;好像没有认真地对两者进行区别和总结&#xff0c;这两者之间也确实很容易混淆&#xff0c;因此结合了很…

Milvus Cloud 问答机器人 上线!构建企业级的 Chatbot

01. 背景 早些时候我们在社区微信群发出了一份关于Milvus Cloud 自动问答机器人的调研问卷。 调研受到了社区同学的积极响应,很快我们就收到了很多热心用户的回复。 基于这些回复,我们整理出了 Milvus Cloud Chatbot 的形态: 以功能使用和文档查询为核心 提供聊天和搜索双形…

version-manager最好用的SDK版本管理器,v0.6.2发布

项目地址&#xff1a;https://github.com/gvcgo/version-manager 中文文档&#xff1a;https://gvcgo.github.io/vdocs/#/zh-cn/introduction 功能特点&#xff1a; 跨平台&#xff0c;支持Windows&#xff0c;Linux&#xff0c;MacOS支持多种语言和工具&#xff0c;省心受到…

react捡起来了

通过脚手架创建react项目&#xff1a; 1.首先看下自己的npm和node版本&#xff1a;cmd打开自己的终端&#xff1a;输入&#xff1a; npm -v 查看npm的版本 node -v查看node的版本 2.不确定自己以前是否安装过creare-react-app&#xff0c;可以通过create-react-app -V(–versio…

【Apache Doris】周FAQ集锦:第 5 期

【Apache Doris】周FAQ集锦&#xff1a;第 5 期 SQL问题数据操作问题运维常见问题其它问题关于社区 欢迎查阅本周的 Apache Doris 社区 FAQ 栏目&#xff01; 在这个栏目中&#xff0c;每周将筛选社区反馈的热门问题和话题&#xff0c;重点回答并进行深入探讨。旨在为广大用户和…

【泛微系统】PC端/移动端JS写法区别

PC端/移动端JS写法区别 1.提交时调用的方法不同: PC端提交时调用:checkCustomize 移动端提交时调用:window.doSubmit_4Mobile 案例:PC端:var checkCustomize2 = checkCustomize;checkCustomize = function (){//这里添加代码//if(1 == 2){// return false;//}return …

【云原生】Kubernetes----Kubernetes集群部署Prometheus 和Grafana

目录 引言 一、环境准备 二、部署node-exporter &#xff08;一&#xff09;创建命名空间 &#xff08;二&#xff09;部署node-exporter 1.获取镜像 2.定义yaml文件 3.创建服务 4.查看监控数据 三、部署Prometheus &#xff08;一&#xff09;创建账号并授权 &…

厂里资讯之app端文章查看

文章列表加载 需求分析 文章布局展示 表结构分析 ap_article 文章基本信息表 ap_article_config 文章配置表 ap_article_content 文章内容表 三张表关系分析 根据数据库设计的表生成对应的实体类 ap_article文章表对应实体 package com.kjz.model.article.pojos;import co…

2024.6.16 机器学习周报

目录 引言 Abstract 文献阅读 1、题目 2、引言 3、创新点 4、匹配问题 5、SuperGlue架构 5.1、注意力图神经网络&#xff08;Attentional Graph Neural Network&#xff09; 5.2、最佳匹配层&#xff08;Optimal matching layer&#xff09; 5.3、损失 6、实验 6.…

【教程】Linux设置进程的优先级

转载请注明出处&#xff1a;小锋学长生活大爆炸[xfxuezhagn.cn] 如果本文帮助到了你&#xff0c;欢迎[点赞、收藏、关注]哦~ 关键指令 sudo chrt -f <优先级> <指令> 示例脚本 当然也可以不是启动Python脚本&#xff0c;普通的指令都可以&#xff0c;可自行适当修…

38、基于卷积神经网络(CNN)的车牌自动识别系统(matlab)

1、原理及流程 1&#xff09;原理 CNN&#xff08;卷积神经网络&#xff09;是一种深度学习模型&#xff0c;可以用于图像识别和分类任务。车牌自动识别系统的原理基本上就是使用CNN模型对车牌图像进行处理和识别。 首先&#xff1a;系统需要收集大量的含有车牌的图像数据作…

cmake target_include_directories 详解

在 CMake 中&#xff0c;target_include_directories 命令用于向特定目标&#xff08;如可执行文件或库&#xff09;添加包含目录&#xff0c;以便编译器能够找到特定目标所需的头文件。 基本语法 target_include_directories(target_name[SYSTEM] [BEFORE]directory1[direct…

什么是知识图谱

文章目录 知识图谱概念知识图谱的发展历史知识图谱的价值知识图谱概念 知识图谱是一种用图模型来描述知识和建模世界万物之间的关联关系的技术方法。知识图谱由节点和边组成。节点可以是实体,如一个人、一本书等,或是抽象的概念,如人工智能、知识图谱等。边可以是实体的属性…

八股操作系统和计算机网络

5.线程间的同步的方式有哪些&#xff1f; 6.PCB(不熟悉) 进程状态 什么是僵尸进程和孤儿进程&#xff1f; 进程调度算法 死锁的理解 举个发生死锁的例子 解决死锁的方式 内存管理做了哪些事情 什么是内存碎片 常见的内存管理 段表通过什么数据结构实现地址映射 分段机制为什么会…

平板消解加热台-温度均匀,防腐蚀-实验室化学分析

DBF系列防腐电热板 是精致路合金加热板块表面经进口高纯实验级PFATeflon氟塑料防腐不粘处理&#xff0c;专为实验室设计的电加热产品&#xff0c;是样品前处理中&#xff0c;加热、消解、煮沸、蒸酸、赶酸等处理的得力助手。可以满足物理、化学、生物、环保、制药、食品、饮品…

星型、环型、总线型和网状型拓扑结构是什么意思?

拓扑结构&#xff08;Topology&#xff09;是指对象在保持某些基本性质不变的情况下&#xff0c;不考虑距离和角度等几何细节的形状和空间关系。换句话说&#xff0c;拓扑结构研究的是物体在连续变形&#xff08;如拉伸、压缩、扭曲等&#xff09;下保持不变的性质。这一点不太…

黑马头条Minio报错non-xml response from server错误的解决方法

今天在写项目的时候&#xff0c;想测试minio上传文件功能是否正常&#xff0c; 但是每次都出现non-xml response from server的错误。 自己也在网上找了很多解决方法&#xff0c;大部分是说用户名和密码的配置问题&#xff0c;但是检查后发现并没有错误。 最后发现是自己的dock…

允许长单词和数字换行

title: 允许长单词和数字换行 date: 2024-06-15 20:18:15 tags: vue3 当文字的张度大于盒子的最大长度&#xff0c;但是由于它是一串数字或者是一串英文字母&#xff0c;通常是不会默认换行的。 在输入的时候我们会经常遇见这样的问题&#xff0c;这个时候就要重新定义一下样…