一、属性简洁表示法
ES5 写法
let name = 'xiao'
let age = 30
let obj = {
name : name,
age : age
}
console. log ( obj)
ES6 简洁写法 对象的属性名 和 属性值的变量名相同,可以简写成 一个属性名
let name = 'xiao'
let age = 30
let obj = {
name,
age
}
console. log ( obj)
二、属性名表达式
当属性名是一个变量时,需要加中括号,才能识别
let s = 'school'
let obj = {
s : 'imooc'
}
console. log ( obj)
let s = 'school'
let obj = {
[ s] : 'imooc'
}
console. log ( obj)
声明对象方法时,可以省略冒号和function
let name = 'xiaoxiao'
let obj = {
name,
study : function ( ) {
console. log ( this . name + '正在学习' )
}
study ( ) {
console. log ( this . name + '正在学习' )
}
}
obj. study ( )
三、Object.is() 判断两个值是否相同
console. log ( Object. is ( 1 , '1' ) )
console. log ( Object. is ( NaN , NaN ) )
console. log ( Object. is ( + 0 , - 0 ) )
let obj1 = {
name : 'xiaoxiao' ,
age : 34
}
let obj2 = {
name : 'xiaoxiao' ,
age : 34
}
console. log ( obj1 === obj2)
console. log ( Object. is ( obj1 , obj2 ) )
obj1 = obj2
console. log ( Object. is ( obj1 , obj2 ) )
四、扩展运算符与Object.assign()
对象的扩展运算符
let x = {
a : 3 ,
b : 4
}
let y = { ... x}
console. log ( y)
Object.assign() 合并对象
let x = {
a : 3 ,
b : 4
}
let y = {
c : 5 ,
a : 8
}
Object. assign ( x, y)
console. log ( x)
五、in 判断数组某个索引是否有值
let arr = [ 1 , 2 , 3 ]
console. log ( 3 in arr)
console. log ( 0 in arr)
六、对象的遍历方式
1. for in 遍历
let obj = {
name : 'xiaoxiao' ,
age : 30 ,
sex : '男'
}
for ( let key in obj) {
console. log ( key, obj[ key] )
}
2. Object.keys() + forEach 遍历
let obj = {
name : 'xiaoxiao' ,
age : 30 ,
sex : '男'
}
Object. keys ( obj) . forEach ( key => {
console. log ( key, obj[ key] )
} )
3. Object.getOwnPropertyNames() + forEach 遍历
let obj = {
name : 'xiaoxiao' ,
age : 30 ,
sex : '男'
}
Object. getOwnPropertyNames ( obj) . forEach ( key => {
console. log ( key, obj[ key] )
} )
4. Reflect.ownKeys() + forEach 遍历
let obj = {
name : 'xiaoxiao' ,
age : 30 ,
sex : '男'
}
Reflect. ownKeys ( obj) . forEach ( key => {
console. log ( key, obj[ key] )
} )