01、数组重组
3 f y2 L8 {$ h% L5 [0 R7 y* J 在使用需要一定程度随机化的算法时,我们通常会发现洗牌数组是一项非常必要的技能。下面的代码片段以 O(n log n) 的复杂度对数组进行混洗。
& _& |% g5 J% lconst 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、复制到剪贴板/ L$ J9 c' w" l. x% G* B- Y
在 Web 应用程序中,复制到剪贴板因其对用户的便利性而迅速普及。
! ]2 V' @" | T# D8 m4 jconst copyToClipboard = (text) =>
navigator.clipboard?.writeText && navigator.clipboard.writeText(text);
// Testing
copyToClipboard("Hello World!"); 注意:根据 caniuse,该方法适用于 93.08% 的全球用户。所以,检查用户的浏览器是否支持 API 是必要的。要支持所有用户,我们可以使用输入并复制其内容。
6 ]: }2 N6 D, W7 h7 g$ K0 b* c! z2 b6 K03、数组去重
0 [' Z6 U* e7 r8 _) o% ^/ p1 ~ 每种语言都有自己的 Hash List 实现,在 JavaScript 中称为 Set。我们可以使用设置数据结构轻松地从数组中获取唯一元素。
/ D# ?- V2 K& }const getUnique = (arr) => [...new Set(arr)];
// Testing
const arr = [1, 1, 2, 3, 3, 4, 4, 4, 5, 5];
console.log(getUnique(arr)); 04、检测暗模式$ n% i8 B* D ~" T# S
随着暗模式的日益流行,如果用户在他们的设备中启用了暗模式,那么将我们的应用程序切换到暗模式是有必要的。
/ F0 t) _6 V: Econst isDarkMode = () =>
window.matchMedia &&
window.matchMedia("(prefers-color-scheme: dark)").matches;
// Testing
console.log(isDarkMode()); 根据 caniuse,matchMedia 的支持率为 97.19%。
5 H9 }: L; W& P; P05、滚动到顶部/ |. v1 s0 _" x1 \3 {
初学者经常发现自己在正确地将元素滚动到视图中时遇到了困难。滚动元素最简单的方法是使用 scrollIntoView 方法。添加行为:“平滑”以获得平滑的滚动动画。
+ s% j9 m9 _7 g2 B- s, o {const scrollToTop = (element) =>
element.scrollIntoView({ behavior: "smooth", block: "start" }); 06、滚动到底部
! f9 w; h0 q6 V9 Z3 C5 b 就像 scrollToTop 方法一样,scrollToBottom 方法可以使用 scrollIntoView 方法轻松实现,只需将块值切换到 end。
7 o1 v6 X9 [* b5 [/ `1 ^const scrollToBottom = (element) =>
element.scrollIntoView({ behavior: "smooth", block: "end" }); 07、生成随机颜色! W# b) y' J0 `. m) J2 l$ e0 Y/ r
我们的应用程序是否依赖随机颜色生成?别再看了,下面的代码片段让你明白了!
, G% J L! j- r# ]; t2 s0 @const generateRandomHexColor = () =>
`#${Math.floor(Math.random() * 0xffffff).toString(16)}`;
|