
編輯整理 | 楊小愛
每個 JS 開發人員都應該使用 javascript one liner 來提高生產力和技能,所以今天我們討論一些可以在日常開發生活中使用的 one liner。
1. 對數組進行排序
使用 sort 方法對數組進行排序非常簡單。
const number = [2,6,3,7,8,4,0];number.sort();// expected output: [0,2,3,4,6,7,8]2.檢查數組中的值
很多時候我們需要檢查值是否存在於數組中,藉助 include 方法。
const array1 = [1, 2, 3];console.log(array1.includes(2));// expected output: true3.過濾數組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. 從數組中查找元素
如果你只需要一個元素,但你在數組中獲得了很多元素,不要擔心 JavaScript 有 find 方法。
const array1 = [5, 12, 8, 130, 44];const found = array1.find(element => element > 10);console.log(found);// expected output: 125. 查找數組中任何元素的索引
要查找數組中元素的索引,您可以簡單地使用 indexOf 方法。
const beasts = ['ant', 'bison', 'camel', 'duck', 'bison'];console.log(beasts.indexOf('bison'));// expected output: 16. 將數組轉換為字符串const elements = ['Fire', 'Air', 'Water'];console.log(elements.join(", "));// expected output: "Fire, Air, Water"7.支票號碼是偶數還是奇數
很容易找出給定的數字是偶數還是奇數。
const isEven = num => num % 2 === 0;orconst isEven = num => !(n & 1);8.刪除數組中的所有重複值
刪除數組中所有重複值的一種非常簡單的方法
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. 合併多個數組的不同方式// merge but don't remove duplicationsconst merge = (a, b) => a.concat(b);orconst merge = (a, b) => [...a, ...b];// merge with remove duplicationsconst merge = (a, b) => [...new Set(a.concat(b))];orconst merge = (a, b) => [...new Set([...a, ...b])];10. 滾動到頁面頂部
有很多方法可以將頁面滾動到頂部。
const goToTop = () => window.scrollTo(0,0, "smooth");orconst scrollToTop = (element) => element.scrollIntoView({behavior: "smooth", block: "start"});// scroll to bottom of the pageconst scrollToBottom = () => window.scrollTo(0, document.body.scrollHeight); 11.複製到剪貼板在 Web 應用程序中,複製到剪貼板因其對用戶的便利性而迅速普及。const copyToClipboard = text => (navigator.clipboard?.writeText ?? Promise.reject)(text);
寫在最後
以上就是我今天跟你分享的11個JavaScript的單行代碼技巧,希望你能從中學到新的知識,如果你覺得有用的話,請點讚我,關注我,並將其與你的朋友分享它,也許能夠幫助到他,最後,感謝你的閱讀,祝編程愉快!學習更多技能
請點擊下方公眾號


