1、新增的API
ES6给Object拓展了许多新的方法,如:
- keys(obj): 获取对象的所有key形成的数组(即所有的属性名)
- values(obj): 获取对象的所有value形成的数组(即所有的值)
- entries(obj): 获取对象的所有key和value形成的二维数组。格式 ‘[[k1,v1],[k2,v2],…]’
- assign(dest,…src) 将多个src对象的值拷贝到dest中。(第一层为深拷贝,第二层为浅拷贝)
const person = {
name: "jack",
age: 21,
language: ['java', 'js', 'css']
}
console.log(Object.keys(person));//["name", "age", "language"]
console.log(Object.values(person));//["jack", 21, Array(3)]
console.log(Object.entries(person));//[Array(2), Array(2), Array(2)]
const target = { a: 1 };
const source1 = { b: 2 };
const source2 = { c: 3 };
//Object.assign方法的第一个参数是目标对象,后面的参数都是源对象
Object.assign(target, source1, source2);
console.log(target);//{a:1,b:2,c:3}
2、声明对象简写
const age = 23
const name = "张三"
//传统
const person1 = { age: age, name: name }
//ES6: 属性名和属性值变量名一样,可以省略
const person2 = { age, name }
console.log(person2);//对象优化.html:37 {age: 23, name: "张三"}
3、对象的函数属性简写
let person3 = {
name: "jack",
// 以前:
eat: function (food) {
console.log(this.name + "在吃" + food);
},
// 箭头函数版,this拿不到,不能使用,得使用对象.属性
eat2: food => console.log(person3.name + "在吃" + food),
// 简写版
eat3(food) {
console.log(this.name + "在吃" + food);
}
}
person3.eat("香蕉");
person3.eat2("苹果")
person3.eat3("橘子");
4、对象拓展运算符
拓展运算符(…)用于取出参数对象所有可遍历属性然后拷贝到当前对象
4.1、拷贝对象(深拷贝)
let p1 = { name: "Amy", age: 15 }
let someone = { ...p1 }
console.log(someone) //{name: "Amy", age: 15}
4.2、合并对象
let age1 = { age: 15 }
let name1 = { name: "Amy" }
//如果两个对象的字段名重复,后面字段值会覆盖前面对象的字段值
let p2 = {name:"zhangsan"}
p2 = {...age1, ...name1 }
console.log(p2) //{age: 15, name: "Amy"}
//覆盖式赋值,直接覆盖掉原有的值
p2 = {name11:"zhangsan"}
p2 = { ...p2,...age1, ...name1 }
console.log(p2) //{name11: "zhangsan", age: 15, name: "Amy"}