新聞中心
今天這篇文章,我想跟大家分享一些強大的 JavaScript 單行代碼,因為使用這些單行代碼可以幫助你提升工作效率,在這篇文章中,我總結(jié)了30個實用的代碼技巧,希望這些代碼技巧對你有用。

公司主營業(yè)務(wù):成都做網(wǎng)站、成都網(wǎng)站設(shè)計、移動網(wǎng)站開發(fā)等業(yè)務(wù)。幫助企業(yè)客戶真正實現(xiàn)互聯(lián)網(wǎng)宣傳,提高企業(yè)的競爭能力。創(chuàng)新互聯(lián)建站是一支青春激揚、勤奮敬業(yè)、活力青春激揚、勤奮敬業(yè)、活力澎湃、和諧高效的團隊。公司秉承以“開放、自由、嚴謹、自律”為核心的企業(yè)文化,感謝他們對我們的高要求,感謝他們從不同領(lǐng)域給我們帶來的挑戰(zhàn),讓我們激情的團隊有機會用頭腦與智慧不斷的給客戶帶來驚喜。創(chuàng)新互聯(lián)建站推出神農(nóng)架林區(qū)免費做網(wǎng)站回饋大家。
那么,我們現(xiàn)在就開始吧。
1. 反轉(zhuǎn)字符串
const reversedString = str => str.split('').reverse().join('');
reversedString("Hello World"); // dlroW olleH2.標題大小寫為字符串
const titleCase = sentence => sentence.replace(/\b\w/g, char => char.toUpperCase());
titleCase("hello world"); // Hello World3. 在變量之間交換值
[a, b] = [b, a];4. 將數(shù)字轉(zhuǎn)換為布爾值
const isTruthy = num => !!num;
isTruthy(0) // False5. 從數(shù)組中獲取唯一值
const uniqueArray = arr => [...new Set(arr)];
uniqueArray([5,5,2,2,2,4,2]) // [ 5, 2, 4 ]6. 截斷字符串
const truncateString = (str, maxLength) => (str.length > maxLength) ? `${str.slice(0, maxLength)}...` : str;
truncateString("Hello World", 8); // Hello Wo...7. 深度克隆對象
const deepClone = obj => JSON.parse(JSON.stringify(obj));
const obj1 = { name: "John", age: 40};
const obj2 = deepClone(obj1);
obj2.age = 20;
console.log(obj1.age); // 40
//This method works for most objects, but it has some limitations. Objects with circular references or functions cannot be converted to JSON, so this method will not work for those types of objects.8. 查找數(shù)組中最后一次出現(xiàn)的位置
const lastIndexOf = (arr, item) => arr.lastIndexOf(item);
lastIndexOf([5, 5, 4 , 2 , 3 , 4], 5) // 19. 合并數(shù)組
const mergeArrays = (...arrays) => [].concat(...arrays);
mergeArrays([5, 5, 4], [2 , 3 , 4]) // [5, 5, 4, 2, 3, 4]10.找到句子中最長的單詞
const longestWord = sentence => sentence.split(' ').reduce((longest, word) => word.length > longest.length ? word : longest, '');
longestWord("The quick brown fox jumped over the lazy dog") // jumped11. 生成一個數(shù)字范圍
const range = (start, end) => [...Array(end - start + 1)].map((_, i) => i + start);
range(5, 15); // [5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]12. 檢查對象是否為空
const isEmptyObject = obj => Object.keys(obj).length === 0;
isEmptyObject({}) // true
isEmptyObject({ name: 'John' }) // false13. 計算數(shù)字的平均值
const average = arr => arr.reduce((acc, num) => acc + num, 0) / arr.length;
average([1, 2, 3, 4, 5, 6, 7, 8, 9]) // 514. 將對象轉(zhuǎn)換為查詢參數(shù)
const objectToQueryParams = obj => Object.entries(obj).map(([key, val]) => `${encodeURIComponent(key)}=${encodeURIComponent(val)}`).join('&');
objectToQueryParams({ page: 2, limit: 10 }) // page=2&limit=1015. 計算數(shù)字的階乘
const factorial = num => num <= 1 ? 1 : num * factorial(num - 1);
factorial(4) // 2416. 計算字符串中的元音數(shù)
const countVowels = str => (str.match(/[aeiou]/gi) || []).length;
countVowels('The quick brown fox jumps over the lazy dog') // 1117. 檢查有效的電子郵件
const isValidEmail = email => /^[\w-]+(\.[\w-]+)*@([\w-]+\.)+[a-zA-Z]{2,7}$/.test(email);
isValidEmail("[email protected]") // true
isValidEmail("example") // false18. 刪除字符串中的空格
const removeWhitespace = str => str.replace(/\s/g, '');
removeWhitespace("H el l o") // Hello19. 檢查閏年
const isLeapYear = year => (year % 4 === 0 && year % 100 !== 0) || (year % 400 === 0);
isLeapYear(2023) // false
isLeapYear(2004) // true20.生成指定長度的隨機字符串
const generateRandomString = length => [...Array(length)].map(() => Math.random().toString(36)[2]).join('')
generateRandomString(8) // 4hq4zm7y21.復制內(nèi)容到剪貼板
const copyToClipboard = (content) => navigator.clipboard.writeText(content)
copyToClipboard("Hello World")22. 獲取 HH:MM:SS 格式的當前時間
const currentTime = () => new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: false })
currentTime() // 19:52:2123. 檢查數(shù)字是偶數(shù)還是奇數(shù)
const isEven = num => num % 2 === 0
isEven(1) // false
isEven(2) // true24.檢測是否為深色模式
const isDarkMode = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches
console.log(isDarkMode) // false25. 滾動到頁面頂部
const goToTop = () => window.scrollTo(0, 0)
goToTop()26. 檢查有效日期
const isValidDate = date => date instanceof Date && !isNaN(date);
isValidDate(new Date("This is not date.")) // false
isValidDate(new Date("08-10-2023")) // true27. 生成日期范圍
const generateDateRange = (startDate, endDate) => Array.from({ length: (endDate - startDate) / (24 * 60 * 60 * 1000) + 1 }, (_, index) => new Date(startDate.getTime() + index * 24 * 60 * 60 * 1000));
generateDateRange(new Date("2023-09-31"), new Date("2023-10-08")) // [Sun Oct 01 2023 05:30:00 GMT+0530 (India Standard Time), Mon Oct 02 2023 05:30:00 GMT+0530 (India Standard Time), Tue Oct 03 2023 05:30:00 GMT+0530 (India Standard Time), Wed Oct 04 2023 05:30:00 GMT+0530 (India Standard Time), Thu Oct 05 2023 05:30:00 GMT+0530 (India Standard Time), Fri Oct 06 2023 05:30:00 GMT+0530 (India Standard Time), Sat Oct 07 2023 05:30:00 GMT+0530 (India Standard Time), Sun Oct 08 2023 05:30:00 GMT+0530 (India Standard Time)]28.計算兩個日期之間的間隔
const dayDiff = (d1, d2) => Math.ceil(Math.abs(d1.getTime() - d2.getTime()) / 86400000)
dayDiff(new Date("2023-10-08"), new Date("1999-04-31")) // 892629. 找出該日期是一年中的第幾天
const dayInYear = (d) => Math.floor((d - new Date(d.getFullYear(), 0, 0)) / 1000 / 60 / 60 / 24)
dayInYear(new Date('2023/10/08'))// 28130.檢查數(shù)組是否相等
const areArraysEqual = (arr1, arr2) => JSON.stringify(arr1) === JSON.stringify(arr2);
areArraysEqual([1, 2, 3], [4, 5, 6]) // false
areArraysEqual([1, 2, 3], [1, 2, 3]) // false結(jié)論
JavaScript 行話是很有價值的工具,可以簡化復雜的任務(wù)并提高代碼的可讀性。通過理解和利用這些技術(shù),不僅展示了自己的熟練程度,還展示了編寫高效、清晰和可維護代碼的能力。
我希望你能發(fā)現(xiàn)它們有用之處,讓它們適應你的項目,幫助你提升開發(fā)效率,不斷優(yōu)化你的解決方案。
文章題目:30個JavaScript單行代碼,讓你成為JavaScript奇才
分享鏈接:http://fisionsoft.com.cn/article/dhppjcs.html


咨詢
建站咨詢
