关于javascript:ES6对象扩展

41次阅读

共计 2002 个字符,预计需要花费 6 分钟才能阅读完成。

明天小编和大家一块聊聊 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])
})

正文完
 0