js常用方法记录

一、异步加载图片

function loadImg(src){
        return new Promise ((reslove,reject)=>{
            const img = new Image()
            img.src = src
            img.onload = ()=>{
                reslove(img)
            }
            img.onerror = reject
            document.body.appendChild(img)
        })
    }
    loadImg('111.png')

二、杨辉三角

for(let i =1;i<5;i++){
        for(let j = 5-i;j>0;j--){
            document.write('^')
        }
        for(let n = 2*i-1;n>0;n--){
            document.write('*')
        }
        document.write(`<br>`)

三、手机号码模糊处理

function phone(number,len){
        return number.slice(0,len*-1)+ '*'.repeat(len)
    }
    console.log(phone('15021889763',4)  //1502188****

四、随机点名

function random(array,start=0,end){
        end = end || array.length
        let index = start+Math.floor(Math.random()*(end-start))
        console.log(array[index])
    }
    let arr = ['张三','李四','王五']
    random(arr,1)

五、时间戳timestamp与日期ISO转换

	//ISO ---> timestamp
   const date = new Date()
    console.log(date*1)
    console.log(Number(date))
    console.log(date.valueOf())
    console.log(date.getTime())
    //timestamp ---> ISO
    const timestamp = date.valueOf()
    console.log(new Date(timestamp))

六、封装日期格式函数 moment.js 优秀的日期处理库

let date = new Date('2020-12-23 12:20:22')
    function formatDate(date,format= 'YYYY-MM-DD HH:mm:ss'){
        let config = {
            YYYY:date.getFullYear(),
            MM:date.getMonth()+1,
            DD:date.getDate(),
            HH:date.getHours(),
            mm:date.getMinutes(),
            ss:date.getSeconds()
        }
        for(let key in config){
            format = format.replace(key,config[key])
        }
        return format
    }
    let newFormatDate = formatDate(date,'YYYY年MM月DD日 HH时mm分ss秒')
    console.log(newFormatDate ) // 2020年12月23日 12时20分22秒
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值