js常用小技巧

数组扁平化

const arr = [1, 2, 3, [4, [5, 6, [7,8]]]];
console.log(arr.flat(Infinity));
// [1, 2, 3, 4, 5, 6, 7, 8] console.log(arr.join().split(',')); // ["1", "2", "3", "4", "5", "6", "7", "8"]
console.log(arr.toString().split(',')); // ["1", "2", "3", "4", "5", "6", "7", "8"]

原来join()、toString()函数式可以跨越层级的,于是便有了方式2、 3

一句代码生成0-100的数组

const arr1 = [...Array(100).keys()] 

一句代码求字符串反转

 let str = 'hello 秦爱德';
 console.log([...str].reverse().join('')) // 德爱秦 olleh

计算相同元素出现次数且以键值对形式展示

const names = ['Alice', 'Bob', 'Tiff', 'Bruce', 'Alice'];
const countNames = names.reduce((allName,name) => {
  if (name in allName) {
    allName[name]++;
  } else {
    allName[name] = 1;
  }

  return allName;
}, {});
console.log(countNames);  // {Alice: 2, Bob: 1, Tiff: 1, Bruce: 1}

数字补0操作

  function toTwo(value,len = 2) {
    return value.padStart(len,'0');
  }
  console.log(toTwo('8')); // 08

  function newToTwo(value,len = 2) {
    return (`0${value}`).slice(-len);
  }
  console.log(newToTwo(1)); // 01
原文地址:https://www.cnblogs.com/ltog/p/14548451.html