15个提升工作效率的JS技巧

Wesley13
• 阅读 513

返回日期数列里与目标数列最近的日期下标

`const getNearestDateIndex = (targetDate, dates) => {
    if (!targetDate || !dates) {
        throw new Error('Argument(s) is illegal !')
    }
    if (!dates.length) {
        return -1
    }
    const distances = dates.map(date => Math.abs(date - targetDate))
    return distances.indexOf(Math.min(...distances))
}

// e.g.
const targetDate = new Date(2019, 7, 20)
const dates = [
new Date(2018, 0, 1),
new Date(2019, 0, 1),
new Date(2020, 0, 1),
]
getNearestDateIndex(targetDate, dates) // 2
`

返回日期数列里最小的日期

`const getMinDate = dates => {
    if (!dates) {
        throw new Error('Argument(s) is illegal !')
    }
    if (!dates.length) {
        return dates
  }
    return new Date(Math.min.apply(null, dates)).toISOString()
}

// e.g.
const dates = [
new Date(2018, 3, 10),
new Date(2019, 3, 10),
new Date(2020, 3, 10),
]
getMinDate(dates) // 2018-04-09T16:00:00.000Z
`

打乱数组

`const arrayShuffle = array => {
    if (!Array.isArray(array)) {
        throw new Error('Argument must be an array')
}
    let end = array.length
    if (!end) {
        return array
    }
    while (end) {
        let start = Math.floor(Math.random() * end--)
        ;[array[start], array[end]] = [array[end], array[start]]
    }
    return array
}

// e.g.
arrayShuffle([1, 2, 3])
`

判断是否支持webp图片格式

`const canUseWebp = () => (document.createElement('canvas').toDataURL('image/webp', 0.5).indexOf('data:image/webp') === 0)

// e.g.
canUseWebp() // 新版的chrome里为true,火狐里为false
`

判断是否是url

`const isUrl = str => /^(((ht|f)tps?)://)?[\w-]+(.[\w-]+)+([\w.,@?^=%&:/+#-]*[\w@?^=%&/+#-])?$/.test(str)

// e.g.
isUrl('https://www.baidu.com') // true
isUrl('https://www') // false
`

判断是否是emoji

`const isEmoji = str => /(\ud83c[\udf00-\udfff])|(\ud83d[\udc00-\ude4f\ude80-\udeff])|[\u2600-\u2B55]/g.test(str)

// e.g.
isEmoji('🌏') // true
isEmoji('earth') // false
`

连字符转驼峰

`const toCamelCase = (str = '', separator = '-') => {
    if (typeof str !== 'string') {
        throw new Error('Argument must be a string')
    }
    if (str === '') {
        return str
    }
    const newExp = new RegExp('\-(\w)', 'g')
    return str.replace(newExp, (matched, $1) => {
        return $1.toUpperCase()
    })
}

// e.g.
toCamelCase('hello-world') // helloWorld
`

驼峰转连字符

``const fromCamelCase = (str = '', separator = '-') => {
    if (typeof str !== 'string') {
        throw new Error('Argument must be a string')
    }
    if (str === '') {
        return str
    }
    return str.replace(/([A-Z])/g, ${separator}$1).toLowerCase()
}

// e.g.
fromCamelCase('helloWorld') // hello-world
``

等级判断

`const getLevel = (value = 0, ratio = 50, levels = '一二三四五') => {
    if (typeof value !== 'number') {
        throw new Error('Argument must be a number')
    }
    const levelHash = '一二三四五'.split('')
    const max = levelHash[levelHash.length - 1]
return levelHash[Math.floor(value / ratio)] || max
}

// e.g.
getLevel1(0) // 一
getLevel1(40) // 一
getLevel(77) // 二
`

事件模拟触发

const event = new Event('click') const body = document.querySelector('body') body.addEventListener('click', ev => {     console.log('biu') }, false) body.addEventListener('touchmove', ev => {     body.dispatchEvent(event) }, false) // 这时候在移动端下滑动手指的时候就会触发click事件

判断dom是否相等

`const isEqualNode = (dom1, dom2) => dom1.isEqualNode(dom2)

/*
    

这是第一个div

    
这是第二个div

    
这是第一个div

*/
const [一, 二, 三,] = document.getElementsByTagName('div')

// e.g.
isEqualNode(一, 二) // false
isEqualNode(一, 三) // true
isEqualNode(二, 三) // false
`

多属性双向绑定

``/*
    


    
*/

const keys = Object
.values(box.attributes)
.map(({name, value}) => ({name, value}))
const cacheData = {}
const properties = keys.reduce((acc, cur) => {
    const obj = {}
    cacheData[cur.name] = box.attributes[cur.name]
    obj[cur.name] = {
        get() {
            return cacheData[cur.name]
        },
        set(data) {
            output.value = ${cur.name}: ${data}
            cacheData[cur.name] = data
        }
    }
    return {
        ...acc,
        ...obj
    }
}, {})
Object.defineProperties(box, properties)

// 当我们修改input相应的属性时,output文字就会变成修改的内容
``

获取指定范围内的随机数

`const getRandom = (min = 0, max = 100) => {
    if (typeof min !== 'number' || typeof max !== 'number') {
        throw new Error('Argument(s) is illegal !')
}
    if (min > max) {
        [min, max] = [max, min]
    }
    return Math.floor(Math.random() * (max - min + 1) + min)
}

// e.g.
getRandom(1, 100) // 89
getRandom(1, 100) // 5
`

文件尺寸格式化

const formatSize = size => {     if (typeof +size !== 'number') {         throw new Error('Argument(s) is illegal !') }     const unitsHash = 'B,KB,MB,GB'.split(',')     let index = 0     while (size > 1024 && index < unitsHash.length) {         size /= 1024         index++     }     return Math.round(size * 100) / 100 + unitsHash[index] } formatSize('10240') // 10KB formatSize('10240000') // 9.77MB

获取数组前/后指定数量元素

``const arrayRange = (array, index, distance = '+') => {
    if (!Array.isArray(array) || typeof index !== 'number' || index < 0) {
        throw new TypeError('Argument(s) is illegal');
    }
    return arr.slice(0, ${distance}${index})
}

arrayRange(['a', 'b', 'c'], 2) // ["a", "b"]
arrayRange(['a', 'b', 'c'], 2, '-') // ["a"]
``

近期

它来了,Vue 3 首个 RC 版本发布!

让Vue项目更丝滑的几个小技巧

15个提升工作效率的JS技巧

若此文有用,何不素质三连❤️

本文分享自微信公众号 - Vue中文社区(vue_fe)。
如有侵权,请联系 support@oschina.cn 删除。
本文参与“OSC源创计划”,欢迎正在阅读的你也加入,一起分享。

点赞
收藏
评论区
推荐文章
blmius blmius
2年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
Karen110 Karen110
2年前
一篇文章带你了解JavaScript日期
日期对象允许您使用日期(年、月、日、小时、分钟、秒和毫秒)。一、JavaScript的日期格式一个JavaScript日期可以写为一个字符串:ThuFeb02201909:59:51GMT0800(中国标准时间)或者是一个数字:1486000791164写数字的日期,指定的毫秒数自1970年1月1日00:00:00到现在。1\.显示日期使用
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
Stella981 Stella981
2年前
Android So动态加载 优雅实现与原理分析
背景:漫品Android客户端集成适配转换功能(基于目标识别(So库35M)和人脸识别库(5M)),导致apk体积50M左右,为优化客户端体验,决定实现So文件动态加载.!(https://oscimg.oschina.net/oscnet/00d1ff90e4b34869664fef59e3ec3fdd20b.png)点击上方“蓝字”关注我
Stella981 Stella981
2年前
HIVE 时间操作函数
日期函数UNIX时间戳转日期函数: from\_unixtime语法:   from\_unixtime(bigint unixtime\, string format\)返回值: string说明: 转化UNIX时间戳(从19700101 00:00:00 UTC到指定时间的秒数)到当前时区的时间格式举例:hive   selec
Stella981 Stella981
2年前
Python time模块 返回格式化时间
常用命令  strftimetime.strftime("%Y%m%d%H:%M:%S",formattime)第二个参数为可选参数,不填第二个参数则返回格式化后的当前时间日期201812112:00:00time.strftime('%H:%M:%S')返回当前时间的时分秒time.strftim
Wesley13 Wesley13
2年前
Java日期时间API系列35
  通过Java日期时间API系列1Jdk7及以前的日期时间类(https://www.oschina.net/action/GoToLink?urlhttps%3A%2F%2Fwww.cnblogs.com%2Fxkzhangsanx%2Fp%2F12032719.html)中得知,Java8以前除了java.sql.Timestamp扩充
Wesley13 Wesley13
2年前
00:Java简单了解
浅谈Java之概述Java是SUN(StanfordUniversityNetwork),斯坦福大学网络公司)1995年推出的一门高级编程语言。Java是一种面向Internet的编程语言。随着Java技术在web方面的不断成熟,已经成为Web应用程序的首选开发语言。Java是简单易学,完全面向对象,安全可靠,与平台无关的编程语言。
Wesley13 Wesley13
2年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
Python进阶者 Python进阶者
3个月前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这