笔记 - 关于JS的零碎贴士

100 阅读1分钟

检测设备是否是触屏设备

检查是否支持触摸

var isTouchDevice = 'ontouchstart' in document.documentElement;
console.log(isTouchDevice);

电脑浏览器支持鼠标事件,但手机不支持。因而可通过检测是否支持触屏区别对待。

检测设备是否为手机

var isMobile = /Android|webOS|iPhone|iPad|BlackBerry/i.test(navigator.userAgent)
if (isMobile) {
    // 当前网页在手机端打开
} else {
    // 当前网页在PC端打开
}

js控制媒体查询

var result = window.matchMedia('(max-width: 768px)');

if (result.matches) {
//console.log('页面宽度小于等于768px');
//写移动端的js效果
} else {
//console.log('页面宽度大于768px');
//写页面宽度大于768px的js效果
}

模板字符串

ES6中,JS有了能够替代引号拼接字符串的模板字符串。

普通字符串和变量拼接

let name = 'Alice';
let id = 1024;
console.log(name + "\'s id is " + id);

模板字符串:利用 ${variable} 拼接

let name = 'Alice';
let id = 1024;
console.log(`${name}'s id is ${id}`);

拼接http模块接收到的数据: Buffer.concat()

当我们使用nodejs http模块接收上传的数据时,可能会收到UTF-8编码,比如“2f 2a 2a 0a 20 2a 20 53 75”。

这时候我们就能使用 Buffer.concat将数据重新拼回字符。

request.on('data', (chunk) =>{
    file_array.push(chunk)
});
request.on('end',() =>{
    const file_string = Buffer.concat(file_array).toString();
    console.log(file_string);
});