ES6新语法之扩展运算符、可选链运算符、函数绑定运算符

目录

1.扩展运算符(...)

1.复制数组(浅拷贝)

2.合并数组 

 3.向对象中添加属性

4.可以使用Math函数来运算

 5.展开字符串

6.解构对象

2.可选链运算符(?.)

1.加变量

2.加数组索引

3.加方法

4.多层嵌套

注意:不能用于赋值

3.函数绑定运算符(::)


1.扩展运算符(...

1.复制数组(浅拷贝)
const arr1 = [1,2,3];
const arr2 = [...arr1];
console.log(arr2); // 打印结果为 [ 1, 2, 3 ],将arr1浅拷贝了一份
2.合并数组 
const arr1 = [1,2,3];
const arr2 = [4,5,6];
const arr3 = [...arr1, ...arr2];
console.log(arr3);// 打印结果为 [ 1, 2, 3, 4, 5, 6 ]
 3.向对象中添加属性
const obj={
    name: "lisa",
    sex: "女"
}
const output = {...user, age: 31};
console.log(output); // 打印结果为 { name:"lisa",sex:"女",age:31}
4.可以使用Math函数来运算
const arr1 = [1, -1, 0, 5, 3];
const min = Math.min(...arr1);
console.log(min); //打印结果为 -1
 5.展开字符串
const str = 'Hello';
const arr = [...str];
console.log(arr); //打印结果为 [ 'H', 'e', 'l', 'l', 'o' ]
6.解构对象
const user = {
    firstname:"Chris",
    rest:{
        lastname:"Bongers",
        age:"31"
    }
}
const {firstname, ...rest} = user;
console.log(firstname);// 打印结果为'Chris'
console.log(rest);// 打印结果为{ lastname: 'Bongers', age: 31 }

2.可选链运算符(?.

可选链运算符?.)允许读取位于连接对象链深处的属性的值,而不必明确验证链中的每个引用是否有效。?. 运算符的功能类似于 . 链式运算符,不同之处在于,在引用为空 (nullish ) (null 或者 undefined) 的情况下不会引起错误,该表达式短路返回值是 undefined。与函数调用一起使用时,如果给定的函数不存在,则返回 undefined

1.加变量

obj?.name       // 如果obj下没有name,也不会报错

2.加数组索引

let arrayItem = arr?.[0]; // 如果arr没有第零项,也不会报错

3.加方法

obj ?. destroyed() 等同于 if (obj){ obj. destroyed()}, 如果obj存在调用destroyed方法,如果不存在,返回undefined

4.多层嵌套
let customer = {
  name: "Carl",
  details: {
    age: 82,
    location: "Paradise Falls" // details 的 address 属性未有定义
  }
};
let customerCity = customer.details?.address?.city;

// … 可选链也可以和函数调用一起使用
let duration = vacations.trip?.getTime?.();
注意:不能用于赋值

object?.property = 1;  // 会报错 Uncaught SyntaxError: Invalid left-hand side in assignment

3.函数绑定运算符(::

“函数绑定”(function bind)运算符,用来取代call、apply、bind调用

函数绑定运算符是并排的两个冒号(::),双冒号左边是一个对象,右边是一个函数。该运算符会自动将左边的对象,作为上下文环境(即this对象),绑定到右边的函数上面

foo::bar;
//  等同于
bar.bind(foo);
foo::bar(...arguments);
//  等同于
bar.apply(foo, arguments);
const hasOwnProperty = Object.prototype.hasOwnProperty;
function hasOwn(obj, key) {
return obj::hasOwnProperty(key);
}

如果双冒号左边为空,右边是一个对象的方法,则等于将该方法绑定在该对象上面。

var method = obj::obj.foo;
//  等同于
var method = ::obj.foo;
let log = ::console.log;
//  等同于
var log = console.log.bind(console);

 由于双冒号运算符返回的还是原对象,因此可以采用链式写法。

//  例一
import { map, takeWhile, forEach } from "iterlib";
getPlayers()
::map(x => x.character())
::takeWhile(x => x.strength > 100)
::forEach(x => console.log(x));
//  例二
let { find, html } = jake;
document.querySelectorAll("div.myClass")
::find("p")
::html("hahaha");
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值