分享 30 个 JavaScript 单行代码片段,提升你的工作效率

前端达人

共 6617字,需浏览 14分钟

 · 2023-10-23

今天这篇文章,我想跟大家分享一些强大的 JavaScript 单行代码,因为使用这些单行代码可以帮助你提升工作效率,在这篇文章中,我总结了30个实用的代码技巧,希望这些代码技巧对你有用。

那么,我们现在就开始吧。

1. 反转字符串

const reversedString = str => str.split('').reverse().join('');reversedString("Hello World"); // dlroW olleH

2.标题大小写为字符串

const titleCase = sentence => sentence.replace(/\b\w/g, char => char.toUpperCase());titleCase("hello world"); // Hello World

3. 在变量之间交换值

[a, b] = [b, a];

4. 将数字转换为布尔值

const isTruthy = num => !!num;isTruthy(0) // False

5. 从数组中获取唯一值

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. 查找数组中最后一次出现的位置

const lastIndexOf = (arr, item) => arr.lastIndexOf(item);lastIndexOf([5, 5, 4 , 2 , 3 , 4], 5) // 1

9. 合并数组

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") // jumped

11. 生成一个数字范围

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({}) // trueisEmptyObject({ name: 'John' }) // false

13. 计算数字的平均值

const average = arr => arr.reduce((acc, num) => acc + num, 0) / arr.length;average([1, 2, 3, 4, 5, 6, 7, 8, 9]) // 5

14. 将对象转换为查询参数

const objectToQueryParams = obj => Object.entries(obj).map(([key, val]) => `${encodeURIComponent(key)}=${encodeURIComponent(val)}`).join('&');objectToQueryParams({ page: 2, limit: 10 }) // page=2&limit=10

15. 计算数字的阶乘

const factorial = num => num <= 1 ? 1 : num * factorial(num - 1);factorial(4) // 24

16. 计算字符串中的元音数

const countVowels = str => (str.match(/[aeiou]/gi) || []).length;countVowels('The quick brown fox jumps over the lazy dog') // 11

17. 检查有效的电子邮件

const isValidEmail = email => /^[\w-]+(\.[\w-]+)*@([\w-]+\.)+[a-zA-Z]{2,7}$/.test(email);isValidEmail("example@email.com") // trueisValidEmail("example") // false

18. 删除字符串中的空格

const removeWhitespace = str => str.replace(/\s/g, '');removeWhitespace("H el l o") // Hello

19. 检查闰年

const isLeapYear = year => (year % 4 === 0 && year % 100 !== 0) || (year % 400 === 0);isLeapYear(2023) // falseisLeapYear(2004) // true

20.生成指定长度的随机字符串

const generateRandomString = length => [...Array(length)].map(() => Math.random().toString(36)[2]).join('')generateRandomString(8) // 4hq4zm7y

21.复制内容到剪贴板

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:21

23. 检查数字是偶数还是奇数

const isEven = num => num % 2 === 0isEven(1) // falseisEven(2) // true

24.检测是否为深色模式

const isDarkMode = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matchesconsole.log(isDarkMode) // false

25. 滚动到页面顶部

const goToTop = () => window.scrollTo(0, 0)goToTop()

26. 检查有效日期

const isValidDate = date => date instanceof Date && !isNaN(date);isValidDate(new Date("This is not date.")) // falseisValidDate(new Date("08-10-2023")) // true

27. 生成日期范围

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")) // 8926

29. 找出该日期是一年中的第几天

const dayInYear = (d) => Math.floor((d - new Date(d.getFullYear(), 0, 0)) / 1000 / 60 / 60 / 24)dayInYear(new Date('2023/10/08'))// 281

30.检查数组是否相等

const areArraysEqual = (arr1, arr2) => JSON.stringify(arr1) === JSON.stringify(arr2);areArraysEqual([1, 2, 3], [4, 5, 6]) // falseareArraysEqual([1, 2, 3], [1, 2, 3]) // false

结论

JavaScript 行话是很有价值的工具,可以简化复杂的任务并提高代码的可读性。通过理解和利用这些技术,不仅展示了自己的熟练程度,还展示了编写高效、清晰和可维护代码的能力。

我希望你能发现它们有用之处,让它们适应你的项目,帮助你提升开发效率,不断优化你的解决方案。

如果您喜欢这篇文章并想阅读更多内容,请务必关注我,我将不定期的分享开发知识。

感谢你的阅读!祝编程愉快!


学习更多技能

请点击下方公众号


浏览 297
点赞
评论
收藏
分享

手机扫一扫分享

举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

举报