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();
【ES6基础语法之对象介绍】注意点:属性的简洁表示法和属性名表达式不能同时使用,否则会报错:
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基础语法之对象的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持脚本之家。
推荐阅读
- ES6基础语法之模块化介绍
- 【基础知识】|【TCP 协议】TCP的三次握手和四次挥手
- C语言进阶|【C语言进阶16——通讯录(基础版、动态内存版、文件管理版)】
- Android基础之自定义Application
- ES6基础语法之Map和Set对象
- ES6基础语法之数组拓展
- ES6基础语法之字符串扩展
- 数学建模|数学建模 线性规划报告_春哥带你学建模数学建模国赛基础入门班(适合小白/零基础)...
- 计算机网络流量控制举例,计算机网络基础(TCP的流量控制)
- 蜂窝系统基础架构