实用技巧(1)

2023-11-10 09:39:38发布
113

1、三木运算符简写

const obj = { config: { set : 1 } } 
const set = obj.config.set ?? 2; // 等价于 const set = obj.config.set ? obj.config.set : 2 


2、对象数组去重

let options = [{
  name: 'tom',
  age: 15,
  date: [1, 2, 3, 4, 5]
}, {
  name: 'tom',
  age: 15,
  date: [1, 2, 3, 4, 5]
},
{
  name: 'marry',
  age: 19,
  date: [1, 4, 5]
}]

options = Array.from(new Set(options.map((item) => {
  return JSON.stringify(item)
}))).map((item) => {
  return JSON.parse(item)
});

console.log(options)


3、断滚动条上下方向

var befortop = 0;
window.addEventListener("scroll", function() {
	var aftertop = document.documentElement ? document.documentElement.scrollTop : document.body.scrollTop;
	if(aftertop - befortop > 0){
		console.log('向下');
	}else{
		console.log('向上');
	}
	befortop = aftertop;
}, false);


4、根据id删除数组重复元素

var data = [{
    name: 'tom',
    id: 1006
}, {
    name: 'marry',
    id: 1007
}, {
    name: 'tom',
    id: 1006
}];

data = data.reduce(function (tempArr, item) {
    if (tempArr.findIndex((ele) => ele.id === item.id) === -1) {
        tempArr.push(item)
    }
    return tempArr
}, []);

console.log(data);


5、使用scrollTo平滑滚动到顶部

window.scrollTo({
  top:0,
  behavior:'smooth'
})


6、判断滚动条是否滚到底部

let scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
let clientHeight = document.documentElement.clientHeight || document.body.clientHeight;
let scrollHeight = document.documentElement.scrollHeight || document.body.scrollHeight;
// 避免没有数据的时候 重复执行 scrollHeight > clientHeight 
if(scrollHeight > clientHeight && scrollTop + clientHeight === scrollHeight) {
  this.loadmore();
}


7、判断pc还是移动端

if ((navigator.userAgent.match(/(iPhone|iPod|Android|ios|iOS|iPad|Backerry| WebOS|Symbian|Windows Phone|Phone)/i))) {
    alert("手机访问");
} else {
    alert("pc访问");
} 

或者

let isMobile = /Android|webOS|iPhone|iPod|BlackBerry/i.test(navigator.userAgent);


8、获取地址栏参数

function getQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return unescape(r[2]); return null;
}


9、倒计时

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>倒计时</title>
</head>

<body>
    <div id="content"></div>
    <script>

        function countdown(endData) {
            const nowData = Date.now();
            if (endData < nowData) {
                throw new Error('the end time must be greater than the current time');
            }
            const d = endData - nowData;
            let h = Math.floor(d / 1000 / 60 / 60);
            let m = Math.floor(d / 1000 / 60 % 60);
            let s = Math.floor(d / 1000 % 60);
            h = h<=9? '0'+ h : h;
            m = m<=9? '0'+ m : m;
            s = s<=9? '0'+ s : s;
            return `${h}:${m}:${s}`;
        }
        
        const content = document.getElementById('content');
        const endData = new Date('2022/01/14 23:59:59').getTime();
        setInterval(()=>{
            content.innerHTML = countdown(endData);
        },1000);
  
    </script>
</body>

</html>


10、a标签直接下载pdf文件

下面的方法有这个限制:不能下载不同域的pdf。如果被下载的文件和项目是在不同的域,则需要设置允许跨域

function handlePdfLink(url, filename) {
    fetch(url, {
        method: 'get',
        responseType: 'arraybuffer',
    }).then(function (res) {
        if (res.status !== 200) {
            return res.json()
        }
        return res.arrayBuffer()
    }).then((blobRes) => {
        // 生成 Blob 对象,设置 type 等信息
        const e = new Blob([blobRes], {
            type: 'application/octet-stream',
            'Content-Disposition': 'attachment'
        })
        // 将 Blob 对象转为 url 并赋予给a标签
        const link = window.URL.createObjectURL(e)
        const a = document.createElement('a');
        a.href = link;
        a.download = filename;
        a.click();
    }).catch(err => {
        console.error(err)
    })
}

// 调用
handlePdfLink('https://file.elecfans.com/web2/M00/4E/EC/poYBAGLCmy-AWxXJAAkvC6Z9dw4690.pdf', 'ttt.pdf')