属性简洁表示法
let name = 'Faker'
let age = '25'
let obj = {
name,
age
}
console.log(obj) // {name: "Faker", age: "25"}
属性名表达式
JS中key-value存取
var map = {};
map['key1'] = 1;
map['key2@'] = 2;
console.log(map['key1']);//结果是1.
console.log(map['key2@']);//结果是2.
//如果遍历map
for(var prop in map){
if(map.hasOwnProperty(prop)){
console.log('key is ' + prop +' and value is' + map[prop]);
}
}
属性名表达式
使用方括号 [ ] 将对象外的变量名称作为属性名
let name = 'Faker'
let age = '25'
let area = 'LCK'
let obj = {
name,
age,
[area]: 'SKT T1'
}
console.log(obj) // {name: "Faker", age: "25", LCK: "SKT T1"}
禁用箭头函数
使用箭头函数会出现this指针错误,使用简写形式即可
let name = 'Faker'
let age = '25'
let area = 'LCK'
let obj = {
name,
age,
area,
draw() {
console.log(area + ':' + name)
}
}
obj.draw() // LCK:Faker
Object.is()
相当于严格等于 === 。但和严格等于又有一些区别。
console.log(Object.is(NaN, NaN)) // true
console.log(Object.is(1, 2)) // false
console.log(Object.is(1, '1')) // false
判断对象和数据时,并不是判断对象的内容,而是内容的地址。
JavaScript变量名储存在栈内存中,而属性值储存在堆内存中,由引用地址完成连接。
// 即使内容一样,仍然返回false,是因为她们的储存地址不同。
let obj_1 = {
name: 'Faker',
age: 25
}
let obj_2 = {
name: 'Faker',
age: 25
}
console.log(Object.is(obj_1,obj_2)) // false
只有当内存地址一样时才会返回true:
let obj_1 = {
name: 'Faker',
age: 25
}
let obj_2 = obj_1
console.log(Object.is(obj_1,obj_2)) // true
扩展运算符 与 Object.assign()
使用扩展运算符将对象中的属性快速提取
let obj_1 = {
name: 'Faker',
age: 25
}
let obj_2 = {
...obj_1, // 使用扩展运算符
team: 'SKT T1'
}
console.log(obj_2) // {name: "Faker", age: 25, team: "SKT T1"}
Object.assign( 目标对象, 被合并的对象 ):用于合并对象
let obj_1 = {
name: 'Faker',
age: 25
}
let obj_2 = {
team: 'SKT T1'
}
console.log(Object.assign(obj_1, obj_2)) // {name: "Faker", age: 25, team: "SKT T1"}
如果有相同的属性,目标对象的原有属性将被覆盖
let obj_1 = {
name: 'Faker',
age: 25
}
let obj_2 = {
name: 'Bang',
team: 'SKT T1'
}
console.log(Object.assign(obj_1, obj_2)) // {name: "Bang", age: 25, team: "SKT T1"}
in
用于判断当前对象是否包含某个属性
let obj_1 = {
name: 'Faker',
age: 25
}
console.log('name' in obj_1) // true
console.log('team' in obj_1) // false
也可用于数组,判断的是该下标是否存在值(用对象的方式去思考~)
let a = [1, 2, 3]
console.log(3 in a) // false
console.log(1 in a) // true
对象的遍历方式
for in
let obj_1 = {
name: 'Faker',
age: 25
}
for (let key in obj_1) {
console.log(key, obj_1[key])
}
// name Faker
// age 25
keys()
let obj_1 = {
name: 'Faker',
age: 25
}
Object.keys(obj_1).forEach(key => {
console.log(key, obj_1[key])
})
// name Faker
// age 25
getOwnPropertyNames()
let obj_1 = {
name: 'Faker',
age: 25
}
Object.getOwnPropertyNames(obj_1).forEach(key => {
console.log(key, obj_1[key])
})
// name Faker
// age 25