实用性较高的JS奇淫巧技,欢迎大家一起讨论补充

567 阅读2分钟

本文旨在记录一些实际开发中实用性较高的奇淫巧技,以下是博主印象比较深刻的,比较少就先不分门别类,博主会持续更新。如有更好的奇淫巧技,欢迎大家一起讨论补充。

1. 交换两个变量

// 交换两个变量,不起中间变量且适用于值类型和引用类型的交换
[x, y] = [y, x]
// or
// x = [y,y=x][0]

2. 数组拼接

let a = [1, 2, 3]
let b = [3, 4, 5]
let c = [6, 7]
a.push(...b, ...c) // 不重新赋值
a = [...a, ...b, ...c]
a = a.concat(b, c)

3. 数组去重

// 可应用于值类型和引用类型
const a = [1,2,3]
const b = [2,3,4,5]
let arr = [...new Set([...a, ...b])]

4. 数组复制

const arr = [1,2,3]
const [...copyArr1] = arr
const copyArr2 = [...arr]

5. 数组解构和赋值结合

const arr = [1, 2, 3, 4, 5]
const [a0,...other] = arr

我们可以通过这一特性完成字符串首字母大小写的功能

// 首字母大写
String.prototype.firstLetter2UpperCase = function () {
    const [letter0, ...otherLetters] = [...this.valueOf()]
    return [letter0.toUpperCase(), ...otherLetters].join('')
}
// 首字母小写
String.prototype.firstLetter2LowerCase = function () {
    const [letter0, ...otherLetters] = [...this.valueOf()]
    return [letter0.toLowerCase(), ...otherLetters].join('')
}

6. 独立对象快速填充数组

// 数组中的每个对象都是独立对象
let arr = new Array(5).fill('').map(() => ({a:1}))

7. 清空数组

const arr = [1,2,3]
// 最高效的清除方法
arr.length = 0

8. 并集、交集和差集

const obj = {
    key: 'value'
}
const a = new Set([1, 2, 4, obj])
const b = new Set([2, 3, 4, obj])

// 并集
const union = new Set([...a, ...b])
// 交集
const intersect = new Set([...a].filter(item => b.has(item)))
// 差集
const diffrence = new Set([...a].filter(item => !b.has(item)))
console.log([...union])
// [ 1, 2, 4, { key: 'value' }, 3 ]
console.log([...intersect])
// [ 2, 4, { key: 'value' } ]
console.log([...diffrence])
// [ 1 ]

9. 过滤掉数组中的假值

JS中假值有: null、undefined、""(空字符串)、+0、-0、NaN

[1,'',{a:1},undefined,{},null,()=>{},0,NaN].filter(Boolean)
// [1, {a:1}, {}, ()=>{}]

10. 默认值设置

const defaultObj = {
    x: 22,
    z: 33
}
const otherSetting = {
    x: 1,
    y: 2
}
const result = {
    ...otherSetting,
    ...defaultObj, // 默认值放在最后面
}
// or
// const result = Object.assign({}, otherSetting, defaultObj)
console.log(result === otherSetting, result)
// false { x: 22, y: 2, z: 33 }

11. 取整

1.1 | 0 	// 1
1.6 | 0 	// 1
-1.1 | 0 	// -1
-1.6 | 0 	// -1

12. 缺省参数校验

function required() {
   	throw new Error('Missing parameter')
}

function foo(p = require()) {
   	console.log(p)
}

13. 多维数组或层次深数据的统一操作

下面举例实际开发中的场景:校验多个节点的输入值不能有非法字符‘$'

const nodes = [{
      name: 'nodeA',
      inputs: [{
        id: 'nodeAinput1',
        value: '$asdfas'
      }, {
        id: 'nodeAinput2',
        value: 'value'
      }]
    },
    {
      name: 'nodeB',
      inputs: [{
        id: 'nodeBinput1',
        value: '$asdfas'
      }, {
        id: 'nodeBinput2',
        value: 'value'
      }]
    },
  ]
  // 取到所有的inputs,便于统一处理,比如进行value的统一校验
  const allInputs = nodes.map(node => node.inputs).flat(Infinity)
  // 找到所有含'$'的input
  const errorInputs = allInputs.filter(input => input.value.includes('$'))