通过使用对象字面量
通过使用对象构造函数
var user = {}; // 'object literal' syntax var name = new Object(); //'object constructor' syntax
function user(name, division) { return { name: name, divison: division }; }
function user(name, division) { return { name, divison }; }
let uname = 'Anil', udivision = 'First'; let user = { uname, udivision }; console.log(user.uname); console.log(user.udivision);
Anil First
var emp = { id : 101, name : 'Amit' } var department = 'dep_name'; emp[department]='Sales'; console.log(emp);
{ id: 101, name: 'Amit', dep_name: 'Sales' }
var department = 'dep_name'; var emp = { id : 102, name : 'Anil', [department]:'Production' } console.log(emp);
{ id: 102, name: 'Anil', dep_name: 'Production' }
let user = { firstName : "Sunil", lastName : "Kumar", fullName : function(){ return this.firstname + " " + this.lastName; } };
let user = { firstName : "Sunil", lastName : "Kumar", fullName(){ return this.firstname + " " + this.lastName; } };
Object.assign() 方法
对象传播语法方法
Object.assign(target, sources)
var obj1 = {1 : "Hello", 2: "World"}; var obj2 = { 3 : "Welcome", 4: "to"}; var obj3 = { 5 : "lidihuo"} // Using Object.assign() var final_obj = Object.assign(obj1, obj2, obj3); console.log(final_obj);
{ '1': 'Hello', '2': 'World', '3': 'Welcome', '4': 'to', '5': 'lidihuo' }
let obj1 = { name: 'Anil', age: 22 }; let cloneobj = Object.assign({}, obj1); cloneobj.age = 32; console.log(obj1); console.log(cloneobj);
{ name: 'Anil', age: 22 } { name: 'Anil', age: 32 }
var new_obj = [...obj1, ...obj2, ...]
var obj1 = {1 : "Hello", 2: "World"}; var obj2 = { 3 : "Welcome", 4: "to"}; var obj3 = { 5 : "lidihuo"} var final_obj = {...obj1, ...obj2, ...obj3}; console.log(final_obj);
{ '1': 'Hello', '2': 'World', '3': 'Welcome', '4': 'to', '5': 'lidihuo' }
var obj = new Object; obj.a = 50; obj.b = 200; delete obj.a; console.log (obj.a);
undefined