十個(gè)殺手級(jí)的實(shí)用JavaScript單行代碼
JavaScript是一門簡(jiǎn)單而復(fù)雜的語(yǔ)言,簡(jiǎn)單是因?yàn)樗泻芏嗫蚣軒?kù)可以使用,復(fù)雜也是因?yàn)樗刑嗟目蚣軒?kù)可以選擇。
很多時(shí)候,我們不知道如何使用,但是,在實(shí)際開(kāi)發(fā)中,我們經(jīng)常用的東西真的不多,在前端領(lǐng)域里,如果CSS能夠?qū)崿F(xiàn)的效果,其實(shí),很多時(shí)候不鼓勵(lì)用JavaScript來(lái)實(shí)現(xiàn)。
但是,如果有時(shí)候,我們用一行代碼就可以實(shí)現(xiàn)的話,我們還是可以考慮一下使用JavaScript來(lái)完成需求任務(wù)。
因此,今天這篇文章,我想與大家分享11個(gè)實(shí)用的JavaScript 單行代碼技巧,也是每個(gè)前端開(kāi)發(fā)人員都應(yīng)該學(xué)會(huì)使用 的技巧,使用這些javascript單行技巧,可以幫助我們提高生產(chǎn)力和技能。
我們不多說(shuō),現(xiàn)在開(kāi)始吧。
1.排序數(shù)組
使用 sort 方法對(duì)數(shù)組進(jìn)行排序非常容易。
const number = [2,6,3,7,8,4,0];number.sort();
// expected output: [0,2,3,4,6,7,8]
2.檢查數(shù)組中的值
很多時(shí)候我們需要在 includes 方法的幫助下檢查值是否存在于數(shù)組中。
const array1 = [1, 2, 3];console.log(array1.includes(2));
// expected output: true
3.過(guò)濾數(shù)組
const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];
const result = words.filter(word => word.length > 6);console.log(result);
// expected output: Array ["exuberant", "destruction", "present"]
4. 從數(shù)組中查找元素
如果你只需要一個(gè)元素,但你在數(shù)組中得到了很多元素,不用擔(dān)心 JavaScript 有 find 方法。
const array1 = [5, 12, 8, 130, 44];const found = array1.find(element => element > 10);console.log(found);
// expected output: 12
5. 查找數(shù)組中任意元素的索引
要查找數(shù)組中元素的索引,您可以簡(jiǎn)單地使用 indexOf 方法。
const beasts = ['ant', 'bison', 'camel', 'duck', 'bison'];console.log(beasts.indexOf('bison'));
// expected output: 1
6. 將數(shù)組轉(zhuǎn)換為字符串
const elements = ['Fire', 'Air', 'Water'];console.log(elements.join(", "));
// expected output: "Fire, Air, Water"
7. 查找數(shù)字是偶數(shù)還是奇數(shù)
很容易找出給定的數(shù)字是偶數(shù)還是奇數(shù)。
const isEven = num => num % 2 === 0;
or
const isEven = num => !(n & 1);
8. 刪除數(shù)組中的所有重復(fù)值
刪除數(shù)組中所有重復(fù)值的一種非常簡(jiǎn)單的方法。
const setArray = arr => [...new Set(arr)];const arr = [1,2,3,4,5,1,3,4,5,2,6];
setArray(arr);
// expected output: [1,2,3,4,5,6]
9.合并多個(gè)數(shù)組的不同方式
// merge but don't remove duplications
const merge = (a, b) => a.concat(b);
or
const merge = (a, b) => [...a, ...b];// merge with remove duplications
const merge = (a, b) => [...new Set(a.concat(b))];
or
const merge = (a, b) => [...new Set([...a, ...b])];
10.滾動(dòng)到頁(yè)面頂部
有很多方法可以將頁(yè)面滾動(dòng)到頂部。
const goToTop = () => window.scrollTo(0,0, "smooth");
or
const scrollToTop = (element) => element.scrollIntoView({behavior: "smooth", block: "start"});// scroll to bottom of the page
const scrollToBottom = () => window.scrollTo(0, document.body.scrollHeight);
11.復(fù)制到剪貼板
在web應(yīng)用程序中,復(fù)制到剪貼板因其對(duì)用戶的便利性而迅速流行起來(lái)。
const copyToClipboard = text => (navigator.clipboard?.writeText ?? Promise.reject)(text);
總結(jié)
以上就是我今天與你分享的全部?jī)?nèi)容,希望對(duì)你有用,如果你覺(jué)得不錯(cuò)的話,請(qǐng)記得點(diǎn)贊我,關(guān)注我,并將這篇文章分享給你的小伙伴,也許能夠幫助到他,與你一起學(xué)習(xí)進(jìn)步。
最后,感謝你的閱讀,編程愉快!