js代码技巧

49 阅读2分钟

1. 多变量赋值

const [test1, test2, test3] = [1, 2, 3];

2. 替换switch

const data = {
  a: callback,
  b: callback,
  c: callback,
};

data[something] && data[something]();

3. 短路运算

let arr;
(arr || [ ]).length  // 0

----------------

return  res.data.data || 'no data'

----------------

isLoggedin && goToHomepage();

4. 变量交换

let x = 'Hello', y = 55;

const temp = x;
x = y;
y = temp;

[x, y] = [y, x];

5. 对象、数组合并

const obj1 = { a: 1, b: 2 };
const obj2 = { ...obj1, d: 4 }; 
// 扩展符对单级对象的拷贝为深拷贝
obj2.a = 3;
obj1.a   // 1
// Object.assign对单级对象的拷贝为深拷贝
Object.assign(obj3, obj1);
obj3.b = 10;
obj1.b   // 2

---------------

const arr1 = [20, 30];
const arr2 = arr1.concat(10, [60, 80]);
const arr3 = [...arr1, 10, 60, 80];

6. 序列生成/数组初始化

//   字母表生成
function Range(start, stop, step) {
  return Array.from({ length: (stop- start) / step + 1}, (_, i) => start + (i * step));
}

Range('A'.charCodeAt(0), 'Z'.charCodeAt(0), 1).map((x) => String.fromCharCode(x))   
// ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']

------------------

// 数组初始化
Array.from({length: 5}, (item, index) => index)   // [0, 1, 2, 3, 4]

7. 平均值计算

const average = (...args) => args.reduce((a, b) => a + b) / args.length;

average(1, 2, 3, 4);  // Result: 2.5

8. 复制文本到剪贴板

navigator.clipboard.writeText(text)'

9. 随机数生成

// 随机16进制
const randomHex = () => `#${Math.floor(Math.random() * 0xffffff).toString(16).padEnd(6, "0")}`;
randomHex(); // Result: #92b008

---------------------

// 随机字符串
const randomString = (len) => {
  const chars = "ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz123456789";
  const strLen = chars.length;
  let randomStr = "";
  for (let i = 0; i < len; i++) {
    randomStr += chars.charAt(Math.floor(Math.random() * strLen));
  }
  return randomStr;
};
randomString(10) // pfkMfjEJ6x

---------------

// 指定范围内随机数

const randomNum = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;
randomNum(1, 10) // 6

10. 数组乱序(洗牌)

const shuffleArray = (arr) => arr.sort(() => Math.random() - 0.5)

shuffleArray([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])

11. 全屏

// 进入全屏
const goToFullScreen = (element) => {
  if (element.requestFullscreen) {
    element.requestFullscreen();
  } else if (element.mozRequestFullScreen) {
    element.mozRequestFullScreen();
  } else if (element.msRequestFullscreen) {
    element.msRequestFullscreen();
  } else if (element.webkitRequestFullscreen) 	{
    element.webkitRequestFullScreen();
  }
};

// 退出全屏
document.exitFullscreen();

12. 类型判断

const isType = (type) => (target) => `[object ${type[0].toUpperCase()}${type.slice(1)}]` === Object.prototype.toString.call(target);

const isArray = isType('array');
const isFunction = isType('Function');
isArray([]);
isFunction(function foo() {});

13. queryParams提取

const url = 'https://juejin.cn/flash-note/list?note_id=7140530613261434916&from=6&editing=1';
const getParams = (url) => JSON.parse(`{"${decodeURI(url.split('?')[1]).replace(/=/g, '":"').replace(/&/g, '","')}}`);
getParams(url); // {"note_id":"7140530613261435000","from":"6","editing":"1"}

14. 判定数组/对象是否为空

// Array
const isNotEmpty = (arr) => arr?.some((x) => x);
// OR
const isNotEmpty = (arr) => Array.isArray(arr) && arr.length > 0;

// Object
const isNotEmpty = (obj) => Reflect.ownKeys(obj).length === 0 && object.constructor === Object;

15. 数组排序

const list = ['Delta', 'alpha', 'ALPHA', 'CHARLIE', 'bravo'];

// 升序排序
list.sort((a, b) => +(a.toLowerCase() > b.toLowerCase()) || +(a.toLowerCase() === b.toLowerCase()) - 1); // ['alpha', 'ALPHA', 'bravo', 'CHARLIE', 'Delta']

// 降序排序
list.sort((a, b) => +(a.toLowerCase() < b.toLowerCase()) || +(a.toLowerCase() === b.toLowerCase()) - 1); // ['Delta', 'CHARLIE', 'bravo', 'alpha', 'ALPHA']

16. json-map转换

// json -> map
const jsonToMap = (json) => new Map(Object.entries(JSON.parse(json)));
const json = '{"user1":"John","user2":"Kate","user3":"Peter"}';
const map = jsonToMap(json); // Map(3) { 'user1' => 'John', 'user2' => 'Kate', 'user3' => 'Peter' }

// map -> json
const mapToJson = (map) => JSON.stringify(Object.fromEntries(map));
const map = new Map([  ['user1', 'John'],  ['user2', 'Kate'],  ['user3', 'Peter'],]);
const json = mapToJson(map); // {"user1":"John","user2":"Kate","user3":"Peter"}

17. 树形结构查找满足条件的子节点

const data = [
    {
        id: '11',
        name: 'text11',
        children: [
            {
                id: '111',
                name: 'text111',
                children: [],
            },
        ],
    },
    {
        id: '22',
        name: 'text22',
        children: [],
    },
];
function findNode(tree, func) {
  for (const node of tree) {
    if (func(node)) return node;
    if (node.children && node.children.length) {
      const res = findNode(node.children, func);
      if (res) return res;
    }
  }
  return null;
}
findNode(data, (id) => id === '111')