ES6的简易写法:对比ES5的写法更加的简洁明了
let name = ‘小明‘ , age = 15; let es5 = { name : name, age : age, }-------------------------------------- let es6 = { name, age }两个的结果都是:{name: "小明", age: 15}
let es5_method = { hello : function(){ console.log(‘hello‘) } } let es6_method = { hello(){ console.log(‘hello‘) } }
ES6对象新增的方法:
//Object.is()方法作用类似于 === console.log(Object.is(‘你好‘,‘你好‘),‘你好‘===‘你好‘) // true true console.log(Object.is([1,2,3],[1,2,3]),[1,2,3]===[1,2,3])// false false let a = { name1 : ‘小明‘},b = { name2 : ‘小强‘},c = { name2 : ‘小刚‘}; //Object.assign()方法将参数第一个对象作为母板其余参数合并到第一个参数中 若键名重复则以最后一个值替换前面的值 console.log(Object.assign(a,b,c)) // {name1: "小明", name2: "小刚"} let test = { name : ‘小强‘, age : 25, hobby : ‘打篮球‘ } for(let [key,value] of Object.entries(test)){ console.log([key,value]) //(2) ["name", "小强"] (2) ["age", 25] (2) ["hobby", "打篮球"] }
解构赋值:
const obj = { first : ‘第一个‘, second : ‘第二个‘ } const {first,second} = obj; //结果: first => ‘第一个‘ second => ‘第二个‘
const player = { nickname: ‘感情的戏∫我没演技?‘, master: ‘东海龙王‘, skill: [{ skillName: ‘龙吟‘, mp: ‘100‘, time: 6000 },{ skillName: ‘龙卷雨击‘, mp: ‘400‘, time: 3000 },{ skillName: ‘龙腾‘, mp: ‘900‘, time: 60000 }] }; //获取player的属性值 const { nickname } = player; const { master } = player; //skill1 => skill中的第一项josn 以此类推 //const {skill : [skill1,skill2,skill3]} = player; // skillName 表示第二项的 skillName //因为重名了 所以第三项 skillName 用 sklName 替代 // const { skill: [ skill1, { skillName },{ skillName: sklName } ] } = player;
扩展运算符:
const obj = { first : "第一项", second : "第二项", third : "第三项", }; //将除 third 项的其他所有项组合成对象的形式赋值给other const {third,...other} = obj; const obj1 = { one : 1, two : 2 }; //将obj1合并到obj2中 const obj2 = { three : 3, four : 4, ...obj1 };
默认值:
let girlfriend = { name: ‘小红‘, age: undefined, }; //当属性值为undefined或者为定义属性时可以直接给属性赋值 let { name, age = 24, hobby = [‘学习‘] } = girlfriend;
获取多个函数返回值:
function p(){ return [ { name : "小明", age : 15 }, { name : "小红", age : 20 } ] } const [{name : name1},{name : name2}] = p() //结果: name1 => 小明 name2=> 小红
原文地址:https://www.cnblogs.com/rickyctbur/p/11553169.html
时间: 2024-10-01 04:57:59