20个常用JavaScript单行代码

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

  • 使用模运算符%
const isEven = num => num % 2 === 0

isEven(10) // true
isEven(9)  // false
  • 使用位运算符&
const isEven = num => (num & 1) === 0

isEven(12) // true
isEven(11) // false

2.在两个数字之间生成一个随机数

  • 借助Math.random生成随机数.
  • 结果包括最大值最小值.
const getRandomNum = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min

getRandomNum(2, 6)  // 2~6

3.随机生成6位数字验证码

  • 借助Math.random生成随机数,借助padStart填充.
const getCode = Math.floor(Math.random() * 1000000).toString().padStart(6, '0')

getCode // '427523'

4.计算两个日期之间的天数

  • 借助Math.abs取两个日期之间的绝对值,然后除以1000 * 3600 * 24(一天的毫秒值).
  • 参数格式可为yyyy-MM-dd(字符串类型)、yyyy/MM/dd(字符串类型).
const getDays = 
      (date1, date2) => Math.abs(new Date(date1) - new Date(date2)) / (1000 * 3600 * 24)

getDays('2020-11-29', '2021-11-29')  // 365
getDays('2021/01/01', '2021/11/29')  // 332

5.查找日期位于一年中的第几天

  • 借助new Date(+date.slice(0, 4), 0, 0))获取当年最开始的时间,然后除以一天的毫秒数.
const getDayOfYear = 
      date => Math.floor((new Date(date) - new Date(+date.slice(0, 4), 0, 0)) / (1000 * 3600 * 24))

getDayOfYear('2021-02-02')  // 33

6.处理当前时间

  • 借助toTimeString()方法将Date对象的时间部分转换为字符串.
  • hour::minutes::seconds 格式输出当前时间.
const curTime = new Date().toTimeString().slice(0, 8)

curTime  // 15:46:48

7.获取浏览器Cookie的值

  • 借助document.cookie来查找cookie的值.
const getCookie = 
      name =>  `; ${document.cookie}`.split(`; ${name}=`).pop().split(';').shift()

getCookie('_ga')  // GA1.2.1892132709.1631783393

8.将数字转化为千分位格式

  • 借助toLocaleString('en-US')进行转化.
const toMark = num => num.toLocaleString('en-US')

toMark(1213865.123)  // 1,213,865.123

9.数组去重

  • 借助ES6提供的数据结构Set.
const delRepeat = arr => [...new Set(arr)]

delRepeat([1, 2, 2, 3, 3, 3, 4, 5, 5])  // [1, 2, 3, 4, 5]

10.数组合并

  • 两种合并数组的 方法,concat()方法和扩展运算符...
const arr1 = [1, 2]
const arr2 = ['Tom', 'Bob']

const mergeArr = arr1.concat(arr2)
// or
const mergeArr = [].concat(arr1, arr2)
// or
const mergeArr = [...arr1, ...arr2]

mergeArr  // [1, 2, 'Tom', 'Bob']

11.随机排列数组

  • 借助sort()方法及Math.random()打乱数组.
const disorderArr = [1, 5, 10, 25, 40, 100].sort(() => 0.5 - Math.random())

disorderArr  // [10, 5, 100, 40, 25, 1]

12.多维数组转一维数组

  • 借助递归.
const deepFlatten = 
      arr => [].concat(...arr.map(n => (Array.isArray(n) ? deepFlatten(n) : n)))

deepFlatten([1, [2, 3], [4, [5, 6]]])  // [1, 2, 3, 4, 5, 6]

13.检查数组是否为空

  • 先判断是否为数组,再判断数组的长度.
  • 非空数组返回true, 否则为false.
const isEmptyArr = arr => Array.isArray(arr) && arr.length > 0

isEmptyArr([3, 2, 1])  // true
isEmptyArr([])         // false

14.字符串反转

  • split()分割,然后reverse()反转,再join()拼接.
const reverse = str => str.split('').reverse().join('')

reverse('hello world')  // dlrow olleh

15.获取JS语言的实际类型

  • typeof只能判断基本类型,通过Object.prototype.toString可以判断某个对象属于哪种内置类型.
const judgeType = obj => Object.prototype.toString.call(obj).slice(8, -1)

judgeType('')        // String
judgeType(0)         // Number
judgeType()          // Undefined
judgeType(null)      // Null
judgeType({})        // Object
judgeType([])        // Array
judgeType(() => {})  // Function
judgeType(Symbol())  // Symbol

16.身份证的正则表达式

const IDReg = /(^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$)|(^[1-9]\d{5}\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{2}[0-9Xx]$)/;

IDRrg.test(511324200001011111)  // true

17.将RGB转换为十六进制

const colorHex = 
      (r, g, b) => "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1)

colorHex(255, 255, 255)  // #ffffff

18.滚动到页面顶部

  • 借助window.scrollTo(0, 0)方法滚动到顶部.
const goTop = () => window.scrollTo(0, 0)

goTop()

19.将文字复制到剪贴板

  • 借助navigator.clipboard.writeText将文本复制到剪切板.
const copyText = async (text) => await navigator.clipboard.writeText(text)

copyText('hello World')

20.检查设备类型

  • 借助navigator.userAgent判断是移动设备还是电脑设备.
const judgeDeviceType =
      () => /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|OperaMini/i.test(navigator.userAgent) ? 'Mobile' : 'Desktop';

judgeDeviceType()  // Desktop
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值