目錄
1?創建一個對象
2?對象屬性操作
2.1?獲取屬性
第一種方式:.語法
第二種方式:[]語法
2種方式的差異
2.2 設置屬性
2.3 刪除屬性
3 案例
1?創建一個對象
創建一個對象,包含了兩個屬性,兩個方法:
? ? var student={?name:"李白" , //student有一個name屬性,值為"李白"grade:"初一" ,//a、student有一個say屬性,值為一個函數//b、student有一個say方法say:function(){console.log("你好");},run:function(speed){console.log("正在以"+speed+"米/秒的速度奔跑");}}
對象是鍵值對的集合:對象是由屬性和方法構成的 (ps:也有說法為:對象里面皆屬性,認為方法也是一個屬性)
+ name是屬性 ? ?grade是屬性
+ say是方法 ? ? run是方法
2?對象屬性操作
2.1?獲取屬性
第一種方式:.語法
+ student.name ? ? ?獲取到name屬性的值,為:"李白"
+ student.say ? ? ? 獲取到一個函數第二種方式:[]語法
+ student["name"] ? 等價于student.name
+ student["say"] ? ?等價于student.say2種方式的差異
+ .語法更方便,但是坑比較多(有局限性),比如:
? ? - .后面不能使用js中的關鍵字、保留字(class、this、function。。。)
? ? - .后面不能使用數字
```js
? ? var obj={};
? ? obj.this=5; //語法錯誤
? ? obj.0=10; ? //語法錯誤
```+ []語法使用更廣泛
? ? - o1[變量name]
? ? - ["class"]、["this"]都可以隨意使用 `obj["this"]=10`
? ? - [0]、[1]、[2]也可以使用 ? ? ??
? ? ? ? - `obj[3]=50 = obj["3"]=50` ? ??
? ? ? ? - 思考:為什么obj[3]=obj["3"] ?
? ? - 甚至還可以這樣用:["[object Array]"]
? ? ? ? - jquery里面就有這樣的實現
? ? - 也可以這樣用:["{abc}"]
? ? ? ? - 給對象添加了{abc}屬性
2.2 設置屬性
設置屬性
+ `student["gender"]="男"` ? ?等價于: ? ?`student.gender="男"`
? ? - 含義:如果student對象中沒有gender屬性,就添加一個gender屬性,值為"男"
? ? - 如果student對象中有gender屬性,就修改gender屬性的值為"男"
+ 案例1:`student.isFemale=true`
+ 案例2:`student["children"]=[1,2,5]`
+ 案例3:為student添加方法
```js
? ? student.toShanghai=function(){ ??
? ? ? ? console.log("正在去往上海的路上") ??
? ? }
```
2.3 刪除屬性
刪除屬性
+ delete student["gender"] ? ? ?
+ delete student.gender?
3 案例
<!DOCTYPE html> <html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><meta http-equiv="X-UA-Compatible" content="ie=edge"><title>Document</title> </head><body></body> <script>//1、創建對象var person = {gender: "男",height: 185,toShanghai: function () {console.log('去上海啦');}};//2、獲取屬性console.log(person.gender); //"男"console.log(person["height"]); //185//3、設置屬性person.address = "xx市xx區";person.height = 190;//4、刪除屬性delete person.gender;delete person.a; //這段代碼沒有意義,也不會報錯//delete關鍵字只能刪除對象中的屬性,不能刪除變量// var a=100;// delete a;//錯誤的理解//清空對象person = {}; //person對象不再具有任何屬性person = null;//表示將person變量的值賦為null,從此以后person不再是一個對象了 </script></html>