您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
本篇内容介绍了“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进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。