ES6 之 函数扩展(扩展运算符)

扩展运算符是三个点(…),好比rest参数的逆运算,讲一个数组转为用逗号分隔的参数序列

console.log(...[1, 2, 3]);      //1 2 3

console.log(1,...[2,3,4],5);    //1 2 3 4 5

console.log([...document.querySelectorAll('div')]);     //[div, div, div]


# 将一个数组变为参数序列

function push(array, ...items){
    array.push(...items);
    return array;
}
var arr = [1,3];
console.log(push(arr, 1, 3, 4));        //[ 1, 3, 1, 3, 4 ]


function add(x, y) {
    return x + y;
}
var number = [4,38];
console.log(add(...number)) //42

# 替代数组的apply的方法
//es5
function f(x,y,z) {}
var arr = [0,1,2];
f.apply(null,arr);

//es6
f(...arr);

#使用Math简化数组取最大值
console.log(Math.max.apply(null, [14, 3, 7]));      //14

console.log(Math.max(...[14, 3, 7]));               //14

# push函数将一个数组添加到另一个数组尾部(亲测不行)
var arr1=[0,1,2];
var arr2 =[3,4,5];

console.log(Array.prototype.push.apply(arr1, arr2));    //亲测: 6,并未像文中所说的将一个数组追加到另一个数组尾部

console.log(arr1.concat(arr2));         //[ 0, 1, 2, 3, 4, 5 ]

console.log(arr1.push(...arr2));                        // 亲测: 6, 并未像文中所说的将一个数组追加到另一个数组尾部

console.log(new (Date.bind.apply(Date, [null, 2015, 1, 1])));       //2015-01-31T16:00:00.000Z

console.log(new Date(...[2015, 1, 1]));                             //2015-01-31T16:00:00.000Z


# 合并数组
var arr1=[0,1,2];
var arr2 =[3,4,5];

arr1 = arr1.concat(arr2);
console.log(arr1);          //[ 0, 1, 2, 3, 4, 5 ]

console.log([...arr1, ...arr2]);//[ 0, 1, 2, 3, 4, 5 ]

#与解构赋值结合
const [frist, ...rest] = [1,2,3,4,5,6];
console.log(frist); //1
console.log(rest);//[ 2, 3, 4, 5, 6 ]

const [frist, ...rest] = [];
console.log(frist); //undefined
console.log(rest);//[]

const [frist, ...rest] = ["foo"];
console.log(frist); //foo
console.log(rest);//[]

# 类似数组的对象  - Map和Set结构
let map = new Map([
    [1,'one'],
    [2,'two'],
    [3,'three']
])
let arr = [...map.keys()];      //[ 1, 2, 3 ]

# 类似数组的对象  -  Generator函数
var go = function *() {
    yield 1;
    yield 2;
    yield 3;
}
[...go()];      //[1,2,3]

ps:如果没有对iterator接口的对象使用扩展运算符,将会报错

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值