JS 中使用扩展运算符的10种方法,好家伙,点个赞呗!

const output = […arr1, …arr2, …arr3, …arr4];

向数组中添加元素


let arr1 = [‘this’, ‘is’, ‘an’];

arr1 = […arr1, ‘array’];

console.log(arr1);

// [ ‘this’, ‘is’, ‘an’, ‘array’ ]

向对象添加属性


假设你有一个user 的对象,但它缺少一个age属性。

const user = {

firstname: ‘Chris’,

lastname: ‘Bongers’

};

要向这个user对象添加age,我们可以再次利用展开操作符。

const output = {…user, age: 31};

使用 Math() 函数


假设我们有一个数字数组,我们想要获得这些数字中的最大值、最小值或者总和。

const arr1 = [1, -1, 0, 5, 3];

为了获得最小值,我们可以使用展开操作符和 Math.min 方法。

const arr1 = [1, -1, 0, 5, 3];

const min = Math.min(…arr1);

console.log(min);

// -1

同样,要获得最大值,可以这么做:

const arr1 = [1, -1, 0, 5, 3];

const max = Math.max(…arr1);

console.log(max);

// 5

如大家所见,最大值5,如果我们删除5,它将返回3

你可能会好奇,如果我们不使用展开操作符会发生什么?

const arr1 = [1, -1, 0, 5, 3];

const max = Math.max(arr1);

console.log(max);

// NaN

这会返回NaN,因为JavaScript不知道数组的最大值是什么。

rest 参数


假设我们有一个函数,它有三个参数。

const myFunc(x1, x2, x3) => {

console.log(x1);

console.log(x2);

console.log(x3);

}

我们可以按以下方式调用这个函数:

myFunc(1, 2, 3);

但是,如果我们要传递一个数组会发生什么。

const arr1 = [1, 2, 3];

我们可以使用展开操作符将这个数组扩展到我们的函数中。

myFunc(…arr1);

// 1

// 2

// 3

这里,我们将数组分为三个单独的参数,然后传递给函数。

const myFunc = (x1, x2, x3) => {

console.log(x1);

console.log(x2);

console.log(x3);

};

const arr1 = [1, 2, 3];

myFunc(…arr1);

// 1

// 2

// 3

向函数传递无限参数


假设我们有一个函数,它接受无限个参数,如下所示:

const myFunc = (…args) => {

console.log(args);

};

如果我们现在调用这个带有多个参数的函数,会看到下面的情况:

myFunc(1, ‘a’, new Date());

返回:

[

1,

‘a’,

Date {

proto: Date {}

}

]

然后,我们就可以动态地循环遍历参数。

将 nodeList 转换为数组


假设我们使用了展开运算符来获取页面上的所有div

const el = […document.querySelectorAll(‘div’)];

console.log(el);

// (3) [div, div, div]

在这里可以看到我们从dom中获得了3个div

现在,我们可以轻松地遍历这些元素,因为它们是数组了。

const el = […document.querySelectorAll(‘div’)];

el.forEach(item => {

console.log(item);

});

//

//

//

解构对象


假设我们有一个对象user:

const user = {

firstname: ‘Chris’,

lastname: ‘Bongers’,

age: 31

};

现在,我们可以使用展开运算符将其分解为单个变量。

const {firstname, …rest} = user;

console.log(firstname);

console.log(rest);

// ‘Chris’

// { lastname: ‘Bongers’, age: 31 }

这里,我们解构了user对象,并将firstname解构为firstname变量,将对象的其余部分解构为rest变量。

展开字符串


展开运算符的最后一个用例是将一个字符串分解成单个单词。

假设我们有以下字符串:

const str = ‘Hello’;

然后,如果我们对这个字符串使用展开操作符,我们将得到一个字母数组。

const str = ‘Hello’;

const arr = […str];

console.log(arr);

// [ ‘H’, ‘e’, ‘l’, ‘l’, ‘o’ ]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值