無序集合,強調的則是屬性名稱,屬性名稱必須要有相對應的值,用大括號 {}
包覆起來的資料,有key、value
//較常用
var 物件名稱 = {
屬性: 值(字串、陣列、函式、物件、數值...),
}
//值可以是function、array、object....
var userInfo = {
firstName: 'Jay',
lastName: 'Chen', //string
ages: 22,//number
interest: ['聽音樂', '看電影', '運動'],//array
address: { //object
country: '台灣',
city: '台北',
locate: '101'
},
fullName: function(){ //function
return this.firstName + ' ' + this.lastName;
//this是一個物件參考,指物件本身
}
}
用new創建物件
var 物件名稱 = new Object();
var userInfo = new Object();
userInfo.name = 'Jay';
userInfo.age = 23;
console.log(userInfo); //Object { age: 23, name: "Jay" }
console.log(userInfo.name); //Jay
靜態存取,無法用數字、變數存取
var userInfo = {
firstName: 'Jay',
lastName: 'Chen', //string
ages: 22,//number
interest: ['聽音樂', '看電影', '運動'],//array
address: { //object
country: '台灣',
city: '台北',
locate: '101'
},
fullName: function(){ //function
return this.firstName + ' ' + this.lastName;
//this是一個物件參考,指物件本身
}
}
//物件讀取:物件名稱.屬性
//取function
userInfo.fullName(); //Jay Chen
//取陣列
var interest = userInfo.interest[0];
console.log(interest); //聽音樂
動態存取資料,[]可以放字串、變數、數字...方式取值
var userInfo = {
firstName: 'Jay',
lastName: 'Chen', //string
ages: 22,//number
interest: ['聽音樂', '看電影', '運動'],//array
}
var city=['台北','台中','台南','高雄'];
// 取物件裡面的物件
//物件讀取:物件名稱['屬性']
console.log(userInfo['firstName']); //台灣
//傳入變數來取值
var personName = 'firstName';
console.log(userInfo[personName]); //Jay
//動態訪問屬性
for(i=0;i<4;i++){
userInfo["city"+i]=city[i];
}
console.log(userInfo);
var obj = {};
obj.name = 'John';
obj['age'] = 22;
console.log(obj); //{name: 'John', age: 22}
obj.name = 'Jay'; //修改值
console.log(obj);//{name: 'Jay', age: 22}
var obj = {
name: 'Jay',
age: 22,
city: 'Taipei'
}
delete obj.city;
delete obj['age'];
console.log(obj); {name: 'Jay'}