JavaScript 个人笔记

261 阅读2分钟

个人笔记整理,不定时更新

将浮点数(或字符串)转化为整数

~~'1.2'     // 1
~~'1'       // 1
~~1.2       // 1
1.2|0       // 1
'1.2'|0     // 1
'1'|0       // 1

不声明第三个变量的值交换

let a = 2, b = 1;
a = [b, b=a][0];
console.log(`a:${a},b:${b}`);   // a:1,b:2

获取文件的后缀名

function getFileExtension(fileName) {
    let arr = fileName.split('.');
    return arr.length >= 2 ? arr.pop() : '';
}
console.log(getFileExtension('test'));  // ''
console.log(getFileExtension('test.test.txt')); // txt

验证座机号码正则

/((\+\d{2,4}-)?(0\d{1,3}-)\d{7,8})/

// 验证手机和座机
/^(((\+\d{2,4}-)?(0\d{1,3}-)\d{7,8})|(1[3456789]\d{9}))$/

获取当前浏览器信息

window.navigator
// 里面包含当前设备操作系统信息 platform oscpu

JS判断是否为闰年

if (year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0)) {
    // 是闰年
}

JS求当天是本年的第几天

function getDayOfYear() {
    let numOfYear = 0;
    const date = new Date();
    const dateArr = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
    const day = date.getDate();
    const month = date.getMonth() + 1;
    const year = date.getFullYear();
    for ( let i = 1; i < month; i++) {
        numOfYear += dateArr[i];
    }
    numOfYear += day;
    if (month > 2 && (year % 4 === 0) && (year % 100 !== 0 || year % 400 === 0)) {
        numOfYear += 1;
    }
    return numOfYear;
}

深复制

function deepclone(data) {
    if(typeof data === 'object' && data !== null) {
        return Object.prototype.toString.call(data) === '[object Array]' ? [ ...data ] : { ...data };
    } else {
        return data;
    }
}

H5唤起通话,短信等

使用a标签

<a href="tel:188xxxxxxxx">一键拨打号码</a>

<a href="mailto:linxunzyf@gmail.com">一键发送邮件</a>

<a href="sms:188xxxxxxx">一键发送短信</a>

或者使用js

window.location.href = 'tel:18888888888';

window.location.href = 'mailto:linxunzyf@gmail.com';

window.location.href = 'sms:18888888888';

生成随机字符串

function generateRandomAlphaNum(len) {
    let rdmString = "";
    for (; rdmString.length < len; rdmString += Math.random().toString(36).substr(2));
    return rdmString.substr(0, len);
}

// 或者
const RandomId = len => Math.random().toString(36).substr(3, len);

获取URL参数

function getUrlParam(name) {  
    const reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象  
    const r = window.location.search.substr(1).match(reg);  //匹配目标参数 
    return r !== null ? decodeURI(r[2]) : null; //返回参数值 
}

// 或者

// 不兼容 IE 和 Edge Mobile
const params = new URLSearchParams(location.search.replace(/\?/ig, "")); // location.search = "?name=linxun&sex=male"

params.has("name"); // true
params.get("sex"); // "male"

// 或者

// 不兼容 IE
const getUrlParams = (url, key) => new URL(url).searchParams.get(key);

参考URLSearchParams

补零

// 前面补零
const FillZeroStart = (num, len) => num.toString().padStart(len, "0");
const num = FillZeroStart(111, 5);
// num => "00111"

// 后面补零
const FillZeroEnd = (num, len) => num.toString().padEnd(len, "0");
const num = FillZeroEnd(111, 5);
// num => "11100"

2019-08-07 更新

日期相关操作

// 工具函数
const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}
格式化指定日期
/** 
* date: 需要格式化的日期
* format: 日期格式,默认为 -
*/
const formatDate = (date, format = '-') => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()

  return [year, month, day].map(formatNumber).join(format)
}
获取指定日期字符串(n天前/后)
/** 
* dayCount: 天数,可为负数
* format: 日期格式,默认为 -
*/
const getDateStr = (dayCount, format = '-') => {
  const now = new Date();
  now.setDate(now.getDate() + dayCount);  // 获取dayCount天后的日期
  const year = now.getFullYear();
  const month = now.getMonth() + 1;
  const day = now.getDate();

  return [year, month, day].map(formatNumber).join(format)
}

2020-07-28 更新

千分位加逗号

let num = 1234567;
// 方法一
num.toLocaleString();

// 方法二
num.toString().replace(/(\d)(?=(?:\d{3})+$)/g, '$1,');

防止Chrome浏览器自动填充账户密码

<!-- 在弹窗中貌似会无效,不知道为啥 -->
<input type="password" auto-complete="new-password" />
<!-- 这个方法比较简单有效 -->
<input 
    type="password" 
    readonly 
    onfocus="this.removeAttribute('readonly')" 
    onblur="this.setAttribute('readonly', true);"
/>

数组过滤空值

[1, 2, 0, undefined, null, false, ''].filter(Boolean); // [1, 2]