数组去重
利用 Array.from 与 set 去重
const arr = [2, 3, 4, 4, 3]
const newArr = Array.from(new Set(arr))
console.log(newArr) // [2, 3, 4]
数组转对象
const arr = ['a', 'b', 'c']
const obj = { ...arr }
console.log(obj) // { 0: 'a', 1: 'b', 2: 'c' }
转换为数字类型、字符串类型
const age = '18'
const newAge = +age
console.log(typeof newAge) // number
const str = 22
const newStr = str + ''
console.log(typeof newStr) // string
测试代码的运行性能
let start = performance.now()
let sum = 0
for(let i = 0; i < 100000; i++){
sum += 1
}
let end = performance.now()
console.log(start)
console.log(end)
console.log(end - start)
数组扁平化
let arr = [1, [2, 3, [4, [5]]]]
arr.flat(3) // [1, 2, 3, 4, 5]
浮点数转整数
console.log(~~9.33) // 9
console.log(9.33 >> 0) // 9
console.log(9.33 << 0) // 9
console.log(9.33 | 0) // 9
获取数组的最后一项
let arr = [1, 3, 5, 7]
const last = arr.slice(-1)[0]
console.log(last) // 7
避免多条件并列
// 不推荐
if (status === 'red' || status === 'blue' || status === 'green') {
doSomething()
}
// 推荐使用 枚举+includes 的方式
const enums = ['red', 'blue', 'green']
if (enums.includes(status)) {
doSomething()
}