01、数组重组8 f7 l( U* _ ~. d) ?- u3 k$ C7 |
在使用需要一定程度随机化的算法时,我们通常会发现洗牌数组是一项非常必要的技能。下面的代码片段以 O(n log n) 的复杂度对数组进行混洗。' ^' ^7 p6 k& t2 u: w
const shuffleArray = (arr) => arr.sort(() => Math.random() - 0.5);
// Testing
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
console.log(shuffleArray(arr)); 02、复制到剪贴板$ Z$ b: M8 z' k" k$ W P: W9 h
在 Web 应用程序中,复制到剪贴板因其对用户的便利性而迅速普及。) M2 e4 [% f7 R7 I- e# r
const copyToClipboard = (text) =>
navigator.clipboard?.writeText && navigator.clipboard.writeText(text);
// Testing
copyToClipboard("Hello World!"); 注意:根据 caniuse,该方法适用于 93.08% 的全球用户。所以,检查用户的浏览器是否支持 API 是必要的。要支持所有用户,我们可以使用输入并复制其内容。
4 x3 E, K/ n7 p( B03、数组去重
1 K% J5 z# d7 @+ _" F; Z, W6 [. m! f 每种语言都有自己的 Hash List 实现,在 JavaScript 中称为 Set。我们可以使用设置数据结构轻松地从数组中获取唯一元素。
" t: l, j$ F$ g0 R" @; V4 @const getUnique = (arr) => [...new Set(arr)];
// Testing
const arr = [1, 1, 2, 3, 3, 4, 4, 4, 5, 5];
console.log(getUnique(arr)); 04、检测暗模式' K9 ^0 Z( m- d% z, Q( G
随着暗模式的日益流行,如果用户在他们的设备中启用了暗模式,那么将我们的应用程序切换到暗模式是有必要的。
1 }3 W1 }& t9 X5 E m+ Qconst isDarkMode = () =>
window.matchMedia &&
window.matchMedia("(prefers-color-scheme: dark)").matches;
// Testing
console.log(isDarkMode()); 根据 caniuse,matchMedia 的支持率为 97.19%。; f3 m4 @# D4 Q F( K# V U: a
05、滚动到顶部6 g5 g# n! s; v6 K: [
初学者经常发现自己在正确地将元素滚动到视图中时遇到了困难。滚动元素最简单的方法是使用 scrollIntoView 方法。添加行为:“平滑”以获得平滑的滚动动画。
4 p$ c7 l) @# v' V: r) D8 n; Yconst scrollToTop = (element) =>
element.scrollIntoView({ behavior: "smooth", block: "start" }); 06、滚动到底部! o0 R7 a$ m9 e8 c/ Z5 j* z
就像 scrollToTop 方法一样,scrollToBottom 方法可以使用 scrollIntoView 方法轻松实现,只需将块值切换到 end。
3 e5 R* z! H& X* O/ R& p4 {const scrollToBottom = (element) =>
element.scrollIntoView({ behavior: "smooth", block: "end" }); 07、生成随机颜色
3 j- t G5 r% {1 P6 a 我们的应用程序是否依赖随机颜色生成?别再看了,下面的代码片段让你明白了!
4 \: @! w5 {% N, ^7 A, c4 Kconst generateRandomHexColor = () =>
`#${Math.floor(Math.random() * 0xffffff).toString(16)}`;
|