您好,登錄后才能下訂單哦!
本篇內容介紹了“ES6對象如何使用”的有關知識,在實際案例的操作過程中,不少人都會遇到這樣的困境,接下來就讓小編帶領大家學習一下如何處理這些情況吧!希望大家仔細閱讀,能夠學有所成!
JavaScript中對象:
var person={name:"Jack",age:20};
或:
var name = "jack"; var age = 20; var person = {name:name,age:age}; console.log(person.age); //20
ES6中的簡潔表示:
let [name,age]=["jack",20]; let person = {name,age}; //等同person = {name: name,age: age} console.log(person.age); //20
JavaScript中對象方法:
var person = { SayHi:function() { console.log("hi"); } } person.SayHi(); //hi
ES6中簡潔表示:
let person = { SayHi() { console.log("hi"); } } person.SayHi();
ES6允許用表達式作為屬性名,但是一定要將表達式放在方括號內:
var person = {["na"+"me"]:"jack",["a"+"ge"]:20}; console.log(person.age);
或
let str = "Hi"; let person = { ["Say"+str](){ console.log("hi"); } } person.SayHi();
注意點:屬性的簡潔表示法和屬性名表達式不能同時使用,否則會報錯:
let [name,age]=["jack",20]; let person = {["na"+"me"],["a"+"ge"]}; //報錯
取出參數對象所有可遍歷屬性然后拷貝到當前對象:
let stu1 = {name:"Jack",age:20,sex:"男"}; let stu2 = {...stu1}; console.log(stu2); //{name: "Jack", age: 20,sex:"男"}
合并兩個對象:
let stu1BasicInfo = {name:"Jack",age:20,sex:"男"}; let stu1DetailInfo = {phone:"13524521457",mail:"ldh@163.com"}; let stu = {...stu1BasicInfo,...stu1DetailInfo}; console.log(stu); //{name:"Jack",age:20,sex:"男",phone:"13524521457",mail:"ldh@163.com"}
拷貝對象時支持添加屬性:
let stu1 = {name:"Jack",age:20,sex:"男"}; let stu2 = {...stu1,phone:"13554785452"}; console.log(stu2); //{name:"Jack",age:20,sex:"男",phone:"13554785452"}
添加的屬性在拓展運算符后面,取添加的屬性:
let stu1 = {name:"Jack",age:20,sex:"男"}; let stu2 = {...stu1,name:"rose",phone:"13554785452"}; console.log(stu2); //{name:"rose",age:20,sex:"男",phone:"13554785452"}
添加的屬性在拓展運算度前面,取擴展運算符內容:
let stu1 = {name:"Jack",age:20,sex:"男"}; let stu2 = {name:"rose",phone:"13554785452",...stu1}; console.log(stu2); //{name:"Jack",phone:"13554785452",age:20,sex:"男"}
“ES6對象如何使用”的內容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業相關的知識可以關注億速云網站,小編將為大家輸出更多高質量的實用文章!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。