常用JS代码段

101 阅读2分钟
  1. 判断是否是IE浏览器
 if (!!window.ActiveXObject || "ActiveXObject" in window){
     alert('IE浏览器')
 }else{
     alert('不是IE浏览器')
 }
  1. 获取当前时间戳
 +new Date()
 new Date().getTime()
 new Date().valueOf()
  1. 用JavaScript打印页面
window.print()
  1. 判断浏览器是否支持HTML 5
!!navigator.geolocation;
//在HTML 5中,navigator.geolocation可以获取设备的当前位置,通过双“!”就可以判断是否支持此API,即是否支持HTML 5
  1. 实现对Windows、Mac、Linux、UNIX操作系统的判断:
var osType = "", 
    windows = (navigator.userAgent.indexOf("Windows",0) != -1)?1:0, 
    mac = (navigator.userAgent.toLowerCase().indexOf("mac",0) != -1)?1:0, 
    linux = (navigator.userAgent.indexOf("Linux",0) != -1)?1:0,   
    unix = (navigator.userAgent.indexOf("X11",0) != -1)?1:0; 
%%
    if (windows) osType = "Windows";  
    else if (mac) osType = "Mac";  
    else if (linux) osType = "Lunix";  
    else if (unix) osType = "Unix";  
    console.log(osType);
//navigator.userAgent表示用户代理。
  1. 使用原生JavaScript判断是否是移动设备浏览器:
var mobileReg = /iphone|ipod|android.*mobile|windows.*phone|blackberry.*mobile/i; 
if((mobileReg.test(window.navigator.userAgent.toLowerCase()))){ 
    alert("移动设备!"); 
}else{ 
    alert("非移动设备!"); 
}

7.数组去重

const uniqueArr = (arr) => [...new Set(arr)];

console.log(uniqueArr(["前端","js","html","js","css","html"]));
// ['前端', 'js', 'html', 'css']
  1. 从url获取参数并转为对象
const getParameters = URL => JSON.parse(`{"${decodeURI(URL.split("?")[1]).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g, '":"')}"}`
  )

getParameters("https://www.google.com.hk/search?q=js+md&newwindow=1");
// {q: 'js+md', newwindow: '1'}

9.检查对象是否为空

const isEmpty = obj => Reflect.ownKeys(obj).length === 0 && obj.constructor === Object;
isEmpty({}) // true
isEmpty({a:"not empty"}) //false
  1. 反转字符串
const reverse = str => str.split('').reverse().join('');
reverse('this is reverse');
// esrever si siht
  1. 生成随机十六进制

const randomHexColor = () => `#${Math.floor(Math.random() * 0xffffff).toString(16).padEnd(6"0")}`
console.log(randomHexColor());
// #a2ce5b

12.检查当前选项卡是否在后台

const isTabActive = () => !document.hiddenisTabActive()
// true|false
  1. 检测元素是否处于焦点
const elementIsInFocus = (el) => (el === document.activeElement);

elementIsInFocus(anyElement)
// 元素处于焦点返回true,反之返回false

14.检查设备类型

const judgeDeviceType =
      () => /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|OperaMini/i.test(navigator.userAgent) ? 'Mobile' : 'PC';

judgeDeviceType()  // PC | Mobile

15.文字复制到剪贴板


const copyText = async (text) => await navigator.clipboard.writeText(text)
copyText('单行代码 前端世界')
  1. 获取选定的文本
const getSelectedText = () => window.getSelection().toString();

getSelectedText();
// 返回选中的内容
  1. 查询某天是否为工作日
const isWeekday = (date) => date.getDay() % 6 !== 0;

isWeekday(new Date(20220311))
// true
  1. 转换华氏/摄氏
  • 将华氏温度转换为摄氏温度
const fahrenheitToCelsius = (fahrenheit) => (fahrenheit - 32) * 5/9;

fahrenheitToCelsius(50);
// 10
  • 将摄氏温度转华氏温度
const celsiusToFahrenheit = (celsius) => celsius * 9/5 + 32;

celsiusToFahrenheit(100)
// 212
  1. 两日期之间相差的天数

const dayDiff = (date1, date2) => Math.ceil(Math.abs(date1.getTime() - date2.getTime()) / 86400000);

dayDiff(new Date("2021-10-21"), new Date("2022-02-12"))
// Result: 114
  1. 计算数组平均值
const average = (arr) => arr.reduce((a, b) => a + b) / arr.length;
average([1,9,18,36]) //16