【JS】简写

81 阅读4分钟

1.  一行代码完成结构加赋值

let people = { name: null, age: null };
let result = { name: '张三',  age: 16 };

({ name: people.name, age: people.age} = result);
console.log(people) // {"name":"张三","age":16}

2.  对基础数据类型进行解构

const {length : a} = '1234';
console.log(a) // 4

3.  对数组解构快速拿到最后一项值

const arr = [123];
const { 0: first, length, [length - 1]: last } = arr;
first; // 1
last; // 3
length; // 3

4.  使用策略模式替换“胖胖”的if-else或者switch-case

// ==================重构前==================
function getPrice(tag, originPrice) {
    // 新人价格
    if(tag === 'newUser') {
        return originPrice > 50.1 ? originPrice - 50 : originPrice
    }
    // 返场价格
    if(tag === 'back') {
         return originPrice > 200 ? originPrice - 50 : originPrice
    }
    // 活动价格
    if(tag === 'activity') {
        return originPrice > 300 ? originPrice - 100 : originPrice
    }
}

// ==================重构后==================
const priceHandler = {
    newUser(originPrice){
        return originPrice > 50.1 ? originPrice - 50 : originPrice
    },
    back(originPrice){
        return originPrice > 200 ? originPrice - 50 : originPrice
    },
    activity(originPrice){
         return originPrice > 300 ? originPrice - 100 : originPrice
    }
}

function getPrice(tag, originPrice){
    return priceHandler[tag](originPrice)
}

5.  ?.(可选链操作符)??(空值合并操作符)空值赋值运算符??=

6.  给多个变量赋值,简写

// before
let a,b,c
a=1
b=2
c=3
// after
let [a,b,c][1,2,3]

7.  赋值运算符简写

// before
a = a+1
b = b-1
c = c*20
// after
a++
b--
c*=20

8.  promise的finally()方法,在then和catch都需要执行的语句写在finally中

var promise = new Promise(function(resolve, reject) {
    console.log("promise")
    window.setTimeout(function(){
      if (false){
        resolve('huangbiao');
      } else {
        debugger
        reject('error');
      }
    },1000)
  }).then(function(){
    console.log('success');
  }).catch(function(){
    console.log('catch');
  }).finally(function(){
    console.log('finally');
  });

9.  字符串转数字 +‘字符串’

一元加号运算符 ( +) 在其操作数之前并计算其操作数,但如果尚未将其转换为数字,则尝试将其转换为数字。
let a = '23'
+a  // 23

10.  修改对象或数组里的对象属性名

let o = JSON.parse(JSON.stringify(data).replace(/name/g'new_name')) 

11.  计算数字的方:Math.pow简写

const result1 = Math.pow(33// 原来
const result2 = 3 ** 3 // 现在
console.log(result1, result2)

12.  优化indexOf

const names = ["abc""cba""nba""why"]
if (names.indexOf("why") !== -1) {
  console.log("包含why")
}
if (names.includes("why")) {
  console.log("包含why")
}
if (names.includes("why"4)) {
  console.log("包含why")
}

13.  Object.values

const obj = {
  name: "why",
  age: 18,
  height: 1.88
}
console.log(Object.values(obj)) // 'why', 18, 1.88 ]
// 如果传入一个字符串
console.log(Object.values("abc")) // 'a''b''c' ]

14.  Object.entries

const obj = {
  name: "why",
  age: 18,
  height: 1.88
}

console.log(Object.entries(obj)) // [ [ 'name''why' ]'age', 18 ]'height', 1.88 ] ]
for (const entry of Object.entries(obj)) {
  const [key, value] = entry
  console.log(key, value)
}

for (const [key, value] of Object.entries(obj)) {   
    console.log(key, value) 
}

// 如果是一个数组
console.log(Object.entries(["abc""cba""nba"])) // [ [ '0''abc' ]'1''cba' ]'2''nba' ] ]

// 如果是一个字符串
console.log(Object.entries("abc")) // [ [ '0''a' ]'1''b' ]'2''c' ] ]

15.  Object.getOwnPropertyDescriptors

Object.getOwnPropertyDescriptors

16.  在string前面或后面补充内容,将string补充到长度为15,补充内容为‘abc’

const message = "Hello World"

console.log(message.padStart(15, "abc")) // aaaaHello World
console.log(message.padEnd(15, "b")) // Hello Worldbbbb
我们简单具一个应用场景:比如需要对身份证、银行卡的前面位数进行隐藏:
const cardNumber = "3242523524256245223879"
const lastFourNumber = cardNumber.slice(-4)
const finalCardNumber = lastFourNumber.padStart(cardNumber.length, "*")
console.log(finalCardNumber) // ******************3879

17.  多维数组拍平

flat() 方法会按照一个可指定的深度递归遍历数组,并将所有元素与遍历到的子数组中的元素合并为一个新数组返回。
const nums = [10, 20, [5, 8], [[2, 3], [9, 22]], 100]
const newNums1 = nums.flat(1)
const newNums2 = nums.flat(2)

// [ 10, 20, 5, 8, [ 2, 3 ], [ 9, 22 ], 100 ]
console.log(newNums1)
// [ 10, 20, 5, 8, 2, 3, 9, 22, 100 ]
console.log(newNums2)

18.  数组

flatMap() 方法首先使用映射函数映射每个元素,然后将结果压缩成一个新数组
注意一:flatMap是先进行map操作,再做flat的操作;
注意二:flatMap中的flat相当于深度为1const messages = ["Hello World""你好啊 李银河""my name is why"]

const newMessages = messages.flatMap(item => {
  return item.split(" ")
})
console.log(newMessages)
// ["Hello","World","你好啊","李银河","my","name","is","why"]

19.  将entries结构的数组转为obj。Object.fromEntries

const obj = {
  name: "why",
  age: 18,
  height: 1.88
}
const entries = Object.entries(obj)
console.log(entries)
const info = Object.fromEntries(entries)
console.log(info)
实际使用:
const paramsString = 'name=why&age=18&height=1.88'
const searchParams = new URLSearchParams(paramsString)
for (const param of searchParams) {
  console.log(param)
}
const searchObj = Object.fromEntries(searchParams)
console.log(searchObj)

20.  去除前面或后面的空格:trim

const message = "   Hello World   "
console.log(message.trim())
console.log(message.trimStart())
console.log(message.trimEnd())

21. Object.groupBy实现分组

const people = [
  { name: "Alice", age: 28 },
  { name: "Bob", age: 30 },
  { name: "Eve", age: 28 },
];
const peopleByAge = Object.groupBy(people, (person) => person.age);
// 或:const peopleByAge = Object.groupBy(people, ({age}) => age);
//结果:peopleByAge
// {
//   28:[
//      { name: "Alice", age: 28 }, 
//      { name: "Eve", age: 28 }],
//   30:[{ name: "Bob", age: 30 }]
// }
// 找到28岁的:peopleByAge[28]

22. 获取数组中的某个成员Array.prototype.at()

ES2022中新增的at()方法,它的作用是获取数组中的某个成员,它的参数是数组的索引,与直接使用索引的方式不同,它允许我们传递负值,等同于从后面倒数,示例代码如下:

const arr = [1, 2, 3, 4, 5, 6]
console.log(arr.at(-1)) // 6
// 等同于 arr[arr.length - 1]

22. &&= 和||= 和 ??=

f1 &&= '一碗周' // 等同于 str = str && '一碗周' 
f2 ||= '一碗周' // 等同于 str = str || '一碗周' 
f3 ??= '一碗周' // 等同于 str = str ?? '一碗周'

22. 



22. 



22. 



22. 



22.