欢迎来到代码驿站!

JavaScript代码

当前位置:首页 > 网页前端 > JavaScript代码

ES6基础语法之对象介绍

时间:2023-02-06 10:30:45|栏目:JavaScript代码|点击:

一、对象和属性和方法

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:"男"}

上一篇:为何JS操作的href都是javascript:void(0);呢

栏    目:JavaScript代码

下一篇:关于Promise 异步编程的实例讲解

本文标题:ES6基础语法之对象介绍

本文地址:http://www.codeinn.net/misctech/225202.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有