日常积累

185 阅读3分钟

一.字符串转txt文件(blob) 动态创建一个a标签,然后设置download属性,然后把下载的内容转blob 上代码

function exportTxt(text, filename) {
  const eleLink = document.createElement('a');
  eleLink.download = filename;
  eleLink.style.display = 'none';
  // 将内容转为 blob
  const blob = new Blob([text]);
  eleLink.href = URL.createObjectURL(blob);
  document.body.appendChild(eleLink);
  eleLink.click();
  document.body.removeChild(eleLink);
}

二. 判断奇偶

const isEven = num => num%2 === 0;

三. 格式化金钱

1.正则

function formatPrice(price) {
  return String(price).replace(/\B(?=(\d{3})+(?!\d))/g, ',');
}

2.字符串

function formatPrice(price) {
  return String(price)
    .split('')
    .reverse()
    .reduce((prev, next, index) => {
      return (index % 3 ? next : next + ',') + prev;
    });
}

3.js原生api

(999999999).toLocaleString(); // 999,999,999
// 当然还可以更秀一点
const options = {
  style: 'currency',
  currency: 'CNY',
};
(123456).toLocaleString('zh-CN', options);

四.vue深度冻结对象 在 vue 项目开发中,有些不变的常量,我们不想 vue 为他做双向绑定,以减少一些性能上消耗,我们可以把使用 Object.freeze 将对象冻结,此时 vue 将不会对这个对象进行冻结,但是这个冻结只是冻结对象第一层,所以遇到对象层级比较深的话,我们可以写个深度冻结的 api,来对常量对象做一些冻结优化

const deepFreeze = o => {
  const propNames = Object.getOwnPropertyNames(o);
  propNames.forEach(name => {
    const prop = o[name];
    if (typeof prop === 'object' && prop !== null) {
      deepFreeze(prop);
    }
  });
  return Object.freeze(o);
};

五. 脱敏处理 对于一些手机号身份证银行卡号

const encryptReg = (before = 3, after = 4) => {
  return new RegExp('(\\d{' + before + '})\\d*(\\d{' + after + '})');
};
// 使用:'13456789876'.replace(encryptReg(), '$1****$2') -> "134****9876"

六. 下划线和驼峰转换

const toHump = name => {
  return name.replace(/\_(\w)/g, function (all, letter) {
    return letter.toUpperCase();
  });
};

const toLine = name => {
  return name.replace(/([A-Z])/g, '_$1').toLowerCase();
};

七. 判断是否是时间格式

const isDate = str => {
  return typeof str !== 'number' && str !== null && new Date(str) !== 'Invalid Date';
};

八. 两个数结构递归对比

const arr1 = [
    {aaa: 'asdasd', id: '1', c: [{aaa: 'asdasd', id: '11'}, {aaa: 'asdasd', id: '12'}]},
    {aaa: 'asdd', id: '2', c: [{aaa: 'asdasd', id: '21'}, {aaa: 'asdasd', id: '22'}]},
    {aaa: 'asdd', id: '3'},
    {aaa: 'asdd', id: '4'},
    {aaa: 'asdd', id: '5', c: [{aaa: 'asdasd', id: '51'}, {aaa: 'asdasd', id: '52'}]},
]

const arr2 = [
    {aaa: 'asdd', id: '2', c: [{aaa: 'asdasd', id: '21'}, {aaa: 'asdasd', id: '22'}]},
    {aaa: 'asdd', id: '5', c: [{aaa: 'asdasd', id: '51'}, {aaa: 'asdasd', id: '52'}]},
    {aaa: 'asdd', id: '6', c: [{aaa: 'asdasd', id: '61'}, {aaa: 'asdasd', id: '62'}]},
]

function diff (a1, a2) {
    const deep = (arr) => {
        arr.forEach(i => {
           i.dis = false
           const deep2 = (arr2) => {
            arr2.forEach(i2 => {
               if(i2.id === i.id){
                 i.dis = true;
               }
               if(i2.c){
                deep2(i2.c)
               }
            })}
            deep2(a2)
            if(i.c) {
                deep(i.c)
            }
        });
    }
    deep(a1);
}
diff(arr1, arr2);
console.log(arr1);

九.对数组解构快速拿到最后一项值

const arr = [1, 2, 3];  
const { 0: first, length, [length - 1]: last } = arr;  
first; // 1  
last; // 3  
length; // 3

十.dom节点平滑滚动到可是区域,顶部,底部 (原生的scrollTo方法没有动画,类似于锚点跳转,比较生硬,可以通过这个方法会自带平滑的过度效果)

function scrollTo(element) {  
    element.scrollIntoView({ behavior"smooth"block"start" }) // 顶部  
    element.scrollIntoView({ behavior"smooth"block"end" }) // 底部  
    element.scrollIntoView({ behavior"smooth"}) // 可视区域  
}

十一. #### 判断整数的不同方法

/* 1.任何整数都会被1整除,即余数是0。利用这个规则来判断是否是整数。但是对字符串不准确 */  
function isInteger(obj) {  
 return obj%1 === 0  
}  
  
/* 1. 添加一个是数字的判断 */  
function isInteger(obj) {  
 return typeof obj === 'number' && obj%1 === 0  
}  
  
/* 2. 使用Math.round、Math.ceil、Math.floor判断 整数取整后还是等于自己。利用这个特性来判断是否是整数*/  
function isInteger(obj) {  
 return Math.floor(obj) === obj  
}  
  
/* 3. 通过parseInt判断 某些场景不准确 */  
function isInteger(obj) {  
 return parseInt(obj, 10) === obj  
}  
  
/* 4. 通过位运算符*/  
function isInteger(obj) {  
 return (obj | 0) === obj  
}  
  
/* 5.ES6提供了Number.isInteger */

十二. #### 通过css检测系统的主题色从而全局修改样式

/* **@media** 的属性 prefers-color-scheme就可以知道当前的系统主题,当然使用前需要查查兼容性*/
@media (prefers-color-scheme: dark) { //... }  
@media (prefers-color-scheme: light) { //... }