01、数组重组9 w3 }0 A6 n$ i0 ]
在使用需要一定程度随机化的算法时,我们通常会发现洗牌数组是一项非常必要的技能。下面的代码片段以 O(n log n) 的复杂度对数组进行混洗。
4 L' K l! Q3 p4 @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、复制到剪贴板
! i' Q$ y, d; ^5 g4 h% l 在 Web 应用程序中,复制到剪贴板因其对用户的便利性而迅速普及。% n% V) S8 g, z8 y7 x/ _
const copyToClipboard = (text) =>
navigator.clipboard?.writeText && navigator.clipboard.writeText(text);
// Testing
copyToClipboard("Hello World!"); 注意:根据 caniuse,该方法适用于 93.08% 的全球用户。所以,检查用户的浏览器是否支持 API 是必要的。要支持所有用户,我们可以使用输入并复制其内容。
+ E) P- \/ \' `% u5 ^1 u' g03、数组去重
0 {2 T0 l9 L2 `6 H% G% |/ i- |) [6 u 每种语言都有自己的 Hash List 实现,在 JavaScript 中称为 Set。我们可以使用设置数据结构轻松地从数组中获取唯一元素。
" J/ }( l9 u3 Q0 e9 o) c7 J4 l( {const getUnique = (arr) => [...new Set(arr)];
// Testing
const arr = [1, 1, 2, 3, 3, 4, 4, 4, 5, 5];
console.log(getUnique(arr)); 04、检测暗模式9 w; C! z4 z( E! J* D+ }. t: S
随着暗模式的日益流行,如果用户在他们的设备中启用了暗模式,那么将我们的应用程序切换到暗模式是有必要的。3 t4 O- v% L8 y1 B- B, D
const isDarkMode = () =>
window.matchMedia &&
window.matchMedia("(prefers-color-scheme: dark)").matches;
// Testing
console.log(isDarkMode()); 根据 caniuse,matchMedia 的支持率为 97.19%。
9 h$ j+ ?/ E# |* y; v/ u4 N) T9 K05、滚动到顶部
' [( J% U! w/ z+ ?0 X 初学者经常发现自己在正确地将元素滚动到视图中时遇到了困难。滚动元素最简单的方法是使用 scrollIntoView 方法。添加行为:“平滑”以获得平滑的滚动动画。
4 M' `6 L9 q; x7 v/ P6 I7 zconst scrollToTop = (element) =>
element.scrollIntoView({ behavior: "smooth", block: "start" }); 06、滚动到底部
* |8 G2 L4 t5 D, O: y: K 就像 scrollToTop 方法一样,scrollToBottom 方法可以使用 scrollIntoView 方法轻松实现,只需将块值切换到 end。
8 B- m, [6 A* _ M) sconst scrollToBottom = (element) =>
element.scrollIntoView({ behavior: "smooth", block: "end" }); 07、生成随机颜色
' R* J8 X. W2 i: n. b1 O6 A 我们的应用程序是否依赖随机颜色生成?别再看了,下面的代码片段让你明白了!
& a# V; Q3 I: h/ I! G7 Pconst generateRandomHexColor = () =>
`#${Math.floor(Math.random() * 0xffffff).toString(16)}`;
|