今天小编和大家一块聊聊ES6中对对象的扩展语法,还有一些常用的语法,相信在不久的将来,肯定会在Vue中看到对象的影子。大家也可以关注我的微信公众号,蜗牛全栈。
一、属性的简洁表示法:主要针对值用变量表示,并且键和值的变量一致
1、普通对象声明
let obj = {
name:"lilei",
age:34
}
console.log(obj)
2、简洁表示法
let name = "lilei"
let age = 34
let obj = {
name,
age
}
3、属性名表达式:主要针对键为变量的情况,需要将变量加上方括号即可
let s = "school"
let obj = {
name:"lilei",
age:34,
s:"school"
}
console.log(obj) // {name:"lilei",age:34,s:"school"}
let s = "school"
let obj = {
name:"lilei",
age:34,
[s]:"school"
}
console.log(obj) // {name:"lilei",age:34,school:"school"}
4、对象内的函数
let s = "school"
let obj = {
name:"lilei",
age:34,
[s]:"school",
study:function(){
console.log(this.name+"正在学习")
}
}
obj.study() // lilei正在学习
let s = "school"
let obj = {
name:"lilei",
age:34,
[s]:"school",
study:() => {
console.log(this.name+"正在学习")
}
}
obj.study() // 报错:can't read property 'name' of undefind(原因就是箭头函数的this指向问题,参见小编的箭头函数文章)
let s = "school"
let obj = {
name:"lilei",
age:34,
[s]:"school",
study(){
console.log(this.name+"正在学习")
}
}
obj.study() // lilei正在学习
二、Object.is():相当于严格判断的三个等号
console.log(Object.is(2,'2')) // false
console.log(Object.is(NaN,NaN)) // true
console.log(Object.is(+0,-0)) // false
let obj1 = {
name:"lilei",
age:34
}
let obj2 = {
name:"lilei",
age:34
}
console.log(obj1 == obj2) // false
console.log(Object.is(obj1,obj2)) // false 引用类型的堆内存地址不一致
let obj1 = {
name:"lilei",
age:34
}
let obj2 = obj1
console.log(Object.is(obj1,obj2)) // true 引用类型的堆内存地址一致
三、扩展运算符与Object.assign()
let x = {
a:3,
b:4
}
let y = {...x}
console.log(y) // {a:3,b:4}
let x = {
a:3,
b:4
}
let y = {}
Object.assign(y,x)
console.log(y) // {a:3,b:4}
let x = {
a:3,
b:4
}
let y = {
c:5,
a:6
}
Object.assign(y,x)
console.log(y) // {a:6,b:4,c:5}
四、in:判断数组指定下标是否存在值;判断对象是否存在指定键
let x = {
a:3,
b:4
}
console.log("a" in x) // true
let arr = [1,2,3]
console.log(3 in arr) // false 判断下表为3的位置是否有值,而不是值3
五、对象的遍历
方法1
let obj = {
name:"lilei",
age:34,
school:"School"
}
for(let key in obj){
console.log(key,obj[key])
}
方法2
let obj = {
name:"lilei",
age:34,
school:"School"
}
Object.keys(obj).forEach(key => {
console.log(key,obj[key])
})
方法3
let obj = {
name:"lilei",
age:34,
}
Object.getOwnPropertyNames(obj).forEach(key => {
console.log(key,obj[key])
})
方法4
let obj = {
name:"lilei",
age:34,
school:"School"
}
Reflect.ownKeys(obj).forEach(key => {
console.log(key,obj[key])
})
网友评论