JS奇技淫巧

2021-09-29  本文已影响0人  cherubic_c

随机生成字母和数组的组合

Math.random().toString(36).substr(2);

格式化时间

const dateFormatter = (formatter, date) => {
    date = (date ? new Date(date) : new Date)
    const Y = date.getFullYear() + '',
          M = date.getMonth() + 1,
          D = date.getDate(),
          H = date.getHours(),
          m = date.getMinutes(),
          s = date.getSeconds()
    return formatter.replace(/YYYY|yyyy/g, Y)
                    .replace(/YY|yy/g, Y.substr(2, 2))
                    .replace(/MM/g, (M < 10 ? '0' : '') + M)
                    .replace(/DD/g, (D < 10 ? '0' : '') + D)
                    .replace(/HH|hh/g, (H < 10 ? '0' : '') + H)
                    .replace(/mm/g, (m < 10 ? '0' : '') + m)
                    .replace(/ss/g, (s < 10 ? '0' : '') + s)
}

dateFormatter('YYYY/MM/DD hh:mm:ss',new Date()) // 2021/06/21 11:11:17

获取变量的实际类型

const trueTypeOf = (obj) => {
  return Object.prototype.toString.call(obj).slice(8, -1).toLowerCase();
};

console.log(trueTypeOf(''));
// string
console.log(trueTypeOf(0));
// number
console.log(trueTypeOf());
// undefined
console.log(trueTypeOf(null));
// null
console.log(trueTypeOf({}));
// object
console.log(trueTypeOf([]));
// array
console.log(trueTypeOf(0));
// number
console.log(trueTypeOf(() => {}));
// function

1. if多条件判断

// 冗余
if (x === 'abc' || x === 'def' || x === 'ghi' || x ==='jkl') {}

// 简洁
if (['abc', 'def', 'ghi', 'jkl'].includes(x)) {}

2. if...else...

// 冗余
let test: boolean;
if (x > 100) {
    test = true;
} else {
    test = false;
}

// 简洁
let test = x > 10;
let text = x > 10 ? true : false
if(status === 0 || status === 1 || status === 2 || status === 3) {
    console.log('按钮可以点击');
}
// =>

if([0, 1, 2, 3].includes(status)) {
    console.log('按钮可以点击');
}
// status 非数值或数值过大
const statusTextObject = {
    100: '已删除',
    101: '未开始',
    102: '上课中',
    103: '已下课',
    104: '已评估'
}
text = statusTextObject[status] || '--';

// 非数值我们将对象的 key 替换为对应status的值即可。

3. Null, Undefined, 空值检查

// 冗余
if (first !== null || first !== undefined || first !== '') {
    let second = first;
}

// 简洁
let second = first || '';

4. 函数条件调用

// 冗余
function test1() {
  console.log('test1');
};
function test2() {
  console.log('test2');
};
var test3 = 1;
if (test3 == 1) {
  test1();
} else {
  test2();
}

// 简单
(test3 === 1? test1:test2)();

5. switch多条件

// 冗余
switch (data) {
  case 1:
    test1();
  break;

  case 2:
    test2();
  break;

  case 3:
    test();
  break;
  // so on...
}

// 简洁
var data = {
  1: test1,
  2: test2,
  3: test
};

data[anything] && data[anything]();

6. 隐式返回

// 冗余
function getArea(diameter) {
  return Math.PI * diameter
}

// 简洁
getArea = diameter => (
  Math.PI * diameter;
)

7. 普通数组去重&对象数组去重

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

console.log(uniqueArr([1, 2, 3, 1, 2, 3, 4, 5]));
// [1, 2, 3, 4, 5]


const uniqueElementsBy = (arr, fn) =>arr
.reduce((acc, v) => {if (!acc.some(x => fn(v, x))) acc.push(v);return acc;}, []);
 
uniqueElementsBy([{id: 1, name: 'Jhon'}, {id: 2, name: 'sss'}, 
{id: 1, name: 'Jhon'}], (a, b) => a.id == b.id)
// [{id: 1, name: 'Jhon'}, {id: 2, name: 'sss'}]

8. 从数组中取出相对应属性的值

const reducedFilter = (data, keys, fn) =>data.filter(fn)
.map(el =>keys.reduce((acc, key) => {acc[key] =el[key];return acc;}, {}));
const data = [
  {
    id: 1,
    name: 'john',
    age: 24
  },
  {
    id: 2,
    name: 'mike',
    age: 50
  }
];
 
let a = reducedFilter(data, ['id', 'name'], item => item.age > 24); // [{ id: 2, name: 'mike'}]

9.关于 return cur.push(v*2),cur之谜

let arr=[1,2,3,4]
const b=arr.reduce((cur,v)=> [...cur,v*2],[])
const b1=arr.reduce((cur,v)=> {
    //直接 return cur.push(v*2)报错是因为 push返回的不是数组,是push之后的长度
    return cur.push(v*2),cur
},[])
const b2=arr.reduce((res, cur)=> { 
    res.push(cur * 2); 
    return res; 
}, [])
// [2,4,6,8]
上一篇 下一篇

猜你喜欢

热点阅读