0
点赞
收藏
分享

微信扫一扫

JavaScript 学习-17.扩展运算符(...)的使用

前言

JavaScript ES6新增了扩展运算符的语法,扩展运算符(spread)是三个点(...)。

该运算符主要用于,将一个数组转为用逗号分隔的参数序列, 通常用于函数的调用传参。

数组合并

把数组转为分割的参数序列

let a = ["hello", "world", "yoyo"];
console.log(...a) // hello world yoyo

可以用于2个数组的合并

let a = ["hello", "world", "yoyo"];
let b = [2, 3, 4]
c = [...a, ...b]
console.log(c) // ['hello', 'world', 'yoyo', 2, 3, 4]

等价于concat()方法合并

let a = ["hello", "world", "yoyo"];
let b = [2, 3, 4]
c = a.concat(b)
console.log(c) // ['hello', 'world', 'yoyo', 2, 3, 4]

或者在a数组的基础上push另外一个数组b

let a = ["hello", "world", "yoyo"];
let b = [2, 3, 4]
a.push(...b)
console.log(a) // ['hello', 'world', 'yoyo', 2, 3, 4]

数组浅拷贝

可以用于克隆一个数组,相当于浅拷贝

let a = ["hello", "world", "yoyo"];
let b = [...a]; // 浅拷贝
console.log(b); // ['hello', 'world', 'yoyo']

我们可以在a数组的基础上重新得到一个新的数组

let a = ["hello", "world", "yoyo"];
let b = [...a, 'a', 'b']; // 往后面添加新元素
console.log(b); // ['hello', 'world', 'yoyo', 'a', 'b']

let c = [1, 2, ...a]; // 往前面添加新元素
console.log(c); // [1, 2, 'hello', 'world', 'yoyo']

let d = [1, 2, ...a, 'a', 'b'];
console.log(d); // [1, 2, 'hello', 'world', 'yoyo', 'a', 'b']

迭代器(Iterator)转为数组

Map 遍历的时候,keys()方法返回 Map 对象中键的迭代器( MapIterator)。

let m = new Map();
m.set('user', 'yoyo');
m.set(1, 'hello');
m.set(2, 'world');
console.log(m.keys()); // MapIterator {'user', 1, 2}

如果我们希望得到一个数组['user', 1, 2],可以用到扩展运算符(...)

let m = new Map();
m.set('user', 'yoyo');
m.set(1, 'hello');
m.set(2, 'world');

let keys = [...m.keys()]
console.log(keys); // ['user', 1, 2]

函数 rest 参数

如果你能弄清楚python函数参数 里面的 ​​*args​​​ 和 ​​**kwargs​​​ ,那么​​*args​​​ 就相当于 JavaScript里面的 ​​rest​​​ 参数 ​​...args​​。

先看一段python的代码关于​​*arg​​参数的使用

def func(a, *args):
print(a)
print(args)


func(1, 2, 3, 4)
# a 得到 1
# args 得到 (2, 3, 4)

接下来再回到JavaScript里面的 ​​rest​​​ 参数 ​​...args​​ 就很好理解了

function func(a, ...args) {
console.log(a); // 1
console.log(args); // [2, 3, 4]
}

func(1, 2, 3, 4);

函数传4个参数,那么a得到1,...args 得到多余的参数2,3,4,这里的args是一个数组[2, 3, 4]

于是很好理解 rest 参数其实就是得到多余的参数,可以在函数参数里面定义一个不定长参数。

当函数的参数很长时,我们可以把参数写到一个数组arr,传参时候用​​...arr​

function func(a, ...args) {
console.log(a); // 1
console.log(args); // [2, 3, 4]
}

arr = [2, 3, 4];
func(1, ...arr);

使用 rest 参数的时候需要注意顺序,一定要放到函数的最后一个参数位置

字符串转数字

可以用扩展运算符把一个字符串转成数组

let a = 'hello';
let b = [...a];
console.log(b); // ['h', 'e', 'l', 'l', 'o']

期作用相当于遍历了字符串,生成一个数组

对象解构赋值

在对象解构赋值的时候也可以用到

const person = {
name: 'yoyo',
age: 20,
address: function () {
return "上海市"
}
}
let {address, ...info} = person;
console.log(info); // {name: 'yoyo', age: 20}

解构赋值的时候 rest 参数的时候需要注意顺序,要放到最后面。




举报

相关推荐

0 条评论