1、取值
const obj = {
name: '彭于晏',
sex: '男',
age: 18
}
let { age } = obj // 18
如果创建的变量名 和 对象的属性名 不一致
let { age: year } = obj // year = 18
解构的对象 不能是 null undefined
let { age: year } = obj || {}
obj为null和undefined时就赋值{}
2、合并数组、对象
const a = [1, 2, 3];
const b = [1, 5, 6];
const c = [...new Set([...a,...b])] // [1, 2, 3, 5, 6]
const obj1 = {
a: 1
}
const obj2 = {
b: 1
}
const obj = { ...obj1, ...obj2 } // { a: 1, b: 1 }
3、字符串拼接
const name = '小明'
const score = 59
const result = `${name}${score > 60 ? '成绩及格' : '成绩不及格' }`
4、精准搜索用 find
find 找到符合条件之后 不会继续遍历数组
const a = [1, 2, 3, 4, 5]
const result = a.find(item => {
return item === 3 // 返回当前item
}
)
5、扁平化数组
const deps = {
'采购部': [1, 2, 3],
'人事部': [5, 8, 12],
'行政部': [5, 14, 79],
'运输部': [3, 64, 105]
}
let member = Object.values(deps).flat(Infinity) // [1, 2, 3, 5, 8, 12, 5, 14, 79, 3, 64, 105]
Infinity作为flat的参数,无需知道被扁平化的数组的维度
6、 添加对象属性
let obj = {}
let index = 1
obj[`topic${index}`] = '话题内容'
7、?? || 两者之间的区别
A ?? B 空值合并运算符
A 为 null nudefined 时 取 B
A 为 0 '' 时 取 A
A || B
A 为 null undefined 0 '' 时 取 B
8、异步函数
const fn = async () => {
const res1 = await fn1()
const res2 = await fn2()
}
9、移除对象属性
let obj = {
x: 45,
y: 72,
z: 68,
p: 98
}
// Longhand
delete obj.x
delete obj.p
console.log(obj) // { y: 72, z: 68 }
// Shorthand
let { x, p, ...newObj } = obj;
console.log(newObj); // { y: 72, z: 68 }
10、key value 一致时 可写为一个
let firstname = 'Amitav'
let lastname = 'Mishra'
//Longhand
let obj = { firstname: firstname, lastname: lastname }
//Shorthand
let obj = { firstname, lastname }