es6中常用的语法(2)

1、对象的拓展

/* 1、当变量名和属性名一致时,可以简写 */	
let foo = { foo } // es6
let foo = { foo: foo } // es5
/* 2、方法也可以简写 */
const a = {
	method: function() { // es5
	    return "Hello!";
	}
	method(){ //es6
		return "hello"
	}
}
/* 拓展运算符(...)*/
let {x, y, ...z} = {x:1, y:2, a:3, b:4, c:5}
console.log(x) //1
console.log(x) //2
console.log(z) // {a:3, b:4, c:5}

2、运算符的拓展

/* 1、指数运算符 */
console.log(2**3) //8
// 多个运算符时,是从右边开始计算
console.log(2**3**3) // 2^27
/* 2、链判断运算符*/
//每一层都应该要判断是否有
// 错误的写法 
const  firstName = message.body.user.firstName || 'default'
// 正确的写法 
const firstName = (message
  && message.body
  && message.body.user
  && message.body.user.firstName) || 'default';
// 优化的写法  
const firstName = message?.body?.user?.firstName || 'default';

//?. 的常见用法
a?.b
// 等同于
a == null ? undefined : a.b
a?.[x]
// 等同于
a == null ? undefined : a[x]
a?.b()
// 等同于
a == null ? undefined : a.b()
a?.()
// 等同于
a == null ? undefined : a()

3、set

ES6 提供了新的数据结构 Set。它类似于数组,但是成员的值都是唯一的,没有重复的值,set的主要作用有
1、去重

 const arr = [1, 2, 3, 4, 1, 4, 2]
 let res = new Set(arr)
 console.log(res); //[1,2,3,4]
 const aa = 'abcacsa'
 let aaa = [...new Set(aa)].join('')
 console.log(aaa);  //abcs

2、使这个新’数组‘拥有对象的属性

const items = new Set([1, 2, 3, 4, 5, 5, 5, 5]);
items.size // 5

4、map

 // map 其中一种用法:遍历数组的一种方式,方法返回一个新数组,数组中的元素为原始数组元素调用函数处理后的值。
 const arr = [1, 2, 3, 4]
 let res = arr.map(item => item * 2)
 console.log(res);// [2,4,6,8]
 



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值