理解剩余参数语法

2025-06-09

理解剩余参数语法

欢迎使用 Rest 参数语法。它类似于展开运算符!

...除非。

首先声明,我并非...在为 JavaScript 语言中重复使用这个符号辩护。但希望这篇文章能帮助你理解 Spread 和 Rest 之间的区别与相似之处。

休息的用例

假设你想给一个函数传递未知数量的参数,这时候你就需要使用 rest 参数了!

function testRest(arg1, arg2, ...otherArgs) {
   console.log(arg1) // 1
   console.log(arg2) // 2
   console.log(otherArgs) // [3, 4, 5]

}

testRest(1, 2, 3, 4, 5)
Enter fullscreen mode Exit fullscreen mode

在这个例子中arg1,并且arg2按预期传递,然后所有附加参数都被添加到otherArgs数组中。

其中一个好处是它otherArgs真的是一个数组。这意味着你所有的数组函数都可以使用。

您可以查看其中的参数数量。

function testRest(arg1, arg2, ...otherArgs) {
   const numOfArgs = otherArgs.length() // 3

}

testRest(1, 2, 3, 4, 5)
Enter fullscreen mode Exit fullscreen mode

您还可以使用数组原型函数来操作它。map,,,,filterreduceflat

单个额外参数

需要记住的是,它otherArgs总是会创建一个数组。这意味着单个参数将被包装在一个数组中。

function testRest(arg1, arg2, ...otherArgs) {
   console.log(arg1) // 1
   console.log(arg2) // 2
   console.log(otherArgs) // [3]

}

testRest(1, 2, 3)
Enter fullscreen mode Exit fullscreen mode

此外,不包含任何附加参数将导致数组为空。

function testRest(arg1, arg2, ...otherArgs) {
   console.log(arg1) // 1
   console.log(arg2) // 2
   console.log(otherArgs) // []

}

testRest(1, 2)
Enter fullscreen mode Exit fullscreen mode

还记得解构吗?

如果您需要快速刷新解构分配,请查看这篇文章。

事实证明,你可以一起使用解构和 rest 参数。

function testRest(...[first, second, third]) {
   console.log(first) // 1
   console.log(second) // 2
   console.log(third) // 3

}

testRest(1, 2, 3)
Enter fullscreen mode Exit fullscreen mode

请记住,解构需要参数的存在。如果你违反了这一约定,你应该知道会发生什么。

如果不包含解构的预期参数,则会导致未定义的引用。

function testRest(...[first, second, third]) {
   console.log(first) // 1
   console.log(second) // 2
   console.log(third) // undefined

}

testRest(1, 2)
Enter fullscreen mode Exit fullscreen mode

如果您包含超出您所解构范围的论点,那么该论点将被删除。

function testRest(...[first, second, third]) {
   console.log(first) // 1
   console.log(second) // 2
   console.log(third) // 3
   // 4 is not destructured

}

testRest(1, 2, 3, 4)
Enter fullscreen mode Exit fullscreen mode

结论

就是这样!正如你在上面的例子中看到的,rest 和 spread 之间的主要区别在于位置。

展开语法可以出现在函数内部或调用函数时。剩余参数语法仅限于函数签名本身。如果你想确定具体使用的是哪种语法,请记住这一点。

希望这能帮助您更好地理解这些概念。

与往常一样,如果您对此类概念感兴趣,请查看以下一些帖子:

鏂囩珷鏉ユ簮锛�https://dev.to/laurieontech/understanding-rest-parameter-syntax-1apn
PREV
Web Vitals 详解
NEXT
理解 Array.prototype.flatMap 让我们从 map 开始 另一种使用 map 的方法 但不是使用 flatMap!重要结论