JavaScript Object 及相关操作
JavaScript Object提供用户一种定义用户数据类型的方法,JavaScript Object键值对集合的实例,不同于原生数据类型,JavaScript Object可以表现多个或复杂的值,并且这些值可以在其生命期被设置,同时,这些值既可以是标量值也可以是函数、数组或其他对象。本文介绍JavaScript Object的一些相关操作:
定义对象:
// 方式一 var person = { name: "Lambda", education: { primary_school: "LA No.1 Primary", middle_school: "LA No.1 Middle", university: "LA University" }, getEducation: function() { return education; }, experience: [ "Microsoft", "Google", "Apple" ] };
// 方式二 var name = "Lambda"; var experience = ["MS", "Google", "Apple"]; var education = { primary_school: "LA No.1 Primary", middle_school: "LA No.1 Middle", university: "LA University" }; var getEducation = function() { return education; } var person = {name, education, getEducation, experience};
// 方式三 var v1 = "Lambda"; var v2 = { primary_school: "LA No.1 Primary", middle_school: "LA No.1 Middle", university: "LA University" }; var v3 = function() { return v2; } var v4 = ["MS", "Google", "Apple"]; var person = { name: v1, education: v2, getEducation: v3, experience: v4 };
// 方式四,对象构造器 var person = new Object(); person.name = "Lambda"; person.education = { primary_school: "LA No.1 Primary", middle_school: "LA No.1 Middle", university: "LA University" }; person.getEducation = function() { return person.education; } person.experience = ["MS", "Google", "Apple"];
// 方式五,对象构造函数 function Car() { this.brand = "Ford"; this.model = "T"; } var obj = new Car();
// 方式六,Object.create方法 var car = { brand: "Ford", model: "T" }; var car1 = Object.create(car); console.log(car1.brand); // Ford console.log(car1.model); // T console.log(car1); // {} console.log(car); // { brand: 'Ford', model: 'T' } console.log(car.brand); // Ford console.log(car.model); // T
// 方式七,Object.assign方法 var car = { brand: "Ford", model: "T" }; var person = { name: "Lambda", gender: "male" }; var obj = Object.assign(person, car); console.log(obj); // {name: 'Lambda', gender: 'male', brand: 'Ford', model: 'T'}
删除对象属性:
// 删除对象属性 var person = { name: "Lambda", gender: "male", }; console.log(person); // { name: 'Lambda', gender: 'male' } delete person.gender; console.log(person); // { name: 'Lambda' }
对象比较:
JavaScript中,Object是引用类型的,因此,即使两个Object的属性完全相同,它们还是两个完全不同的Object.
// Objects comparing var person1 = { name: "Lambda", gender: "male", }; var person2 = { name: "Lambda", gender: "male", }; console.log(person1 == person2); // false console.log(person1 === person2); // false var person3 = person1; console.log(person3 == person1); // true console.log(person3 === person1); // true
对象解构:
// 对象解构 var person = { name: "Lambda", gender: "male", }; var {name, gender} = person; console.log(name); // Lambda console.log(gender); // male