ES6之rest参数、扩展运算符

本文介绍了ES6中的rest参数和扩展运算符。rest参数允许函数接收不定数量的参数并将其存储在数组中,而扩展运算符可以将数组转化为参数序列,用于函数调用、数组合并及克隆。此外,扩展运算符还能用于将伪数组转换为真数组。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


前言

rest参数与arguments变量相似。ES6引入rest参数代替arguments,获取函数实参。
扩展运算符能将数组转化为参数序列。


一、rest参数

		function namelist1() {
            console.log(arguments);
        }

        function namelist2(...args) {
            console.log(args);
        }

        namelist1('张三', '李四', '王五');
        namelist1('张三', '李四', '王五');

在这里插入图片描述
由此可看出args也是数组,所以它可以跟数组方法filter,some,map,every等连用。
注意!rest参数必须放在参数最后,如下:

	function fn(a, b, ...args) {
            console.log(a);
            console.log(b);
            console.log(args);
        }
        fn(1, 2, 3, 4);

二、扩展运算符

1.将数组转化为逗号分隔的参数序列

代码如下(示例):

	 	const namelist = ['张三', '李四', '王五'];

        function fn() {
            console.log(arguments);
        }
        fn(...namelist); //相当于fn('张三', '李四', '王五')
        console.log(namelist);
        console.log(...namelist);

在这里插入图片描述

2.应用

  • 数组合并
	 	const film = ['失孤', '心灵旅途'];
        const tv = ['盗墓笔记', '秦岭神树'];
        const yule = [...film, ...tv];
        console.log(yule);

在这里插入图片描述

  • 数组的克隆
		const list1 = ['a', 'b', 'c'];
        const list2 = [...list1];
        console.log(list1);
        console.log(list2);

在这里插入图片描述

  • 将伪数组转换为真数组
	<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <div>1</div>
    <div>2</div>
    <div>3</div>
    <script>
        const divs = document.querySelectorAll('div');
        const divlist = [...divs];
        console.log(divs);
        console.log(divlist);
    </script>
</body>

</html>

在这里插入图片描述


总结

以上就是rest参数和扩展运算符的讲解。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

浩泽学编程

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值