五、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:"男"}
本文来自博客园,作者:码农阿亮,转载请注明原文链接:https://www.cnblogs.com/wml-it/p/15967789.html
技术的发展日新月异,随着时间推移,无法保证本博客所有内容的正确性。如有误导,请大家见谅,欢迎评论区指正!
开源库地址,欢迎点亮:
GitHub:https://github.com/ITMingliang
Gitee: https://gitee.com/mingliang_it
GitLab: https://gitlab.com/ITMingliang
建群声明: 本着技术在于分享,方便大家交流学习的初心,特此建立【编程内功修炼交流群】,为大家答疑解惑。热烈欢迎各位爱交流学习的程序员进群,也希望进群的大佬能不吝分享自己遇到的技术问题和学习心得!进群方式:扫码关注公众号,后台回复【进群】。