Skip to Content
JavaScript 经典实例:第三版
book

JavaScript 经典实例:第三版

by Adam D. Scott, Matthew MacDonald, Shelley Powers
September 2022
Intermediate to advanced
585 pages
8h 17m
Chinese
China Electric Power Press Ltd.
Content preview from JavaScript 经典实例:第三版
150
6
6.4.3
讨论
剩余参数不一定是函数的唯一参数,但必须是最后一个参数。剩余参数收集传给函
数的全部额外参数,添加到一个新数组中。
过去,
JavaScript
开发人员使用
arguments
对象实现类似的功能。
arguments
对象(严
格来说是
Function.arguments
属性)在每个函数中都可用,通过类似数组的方式获
取参数。然而,
arguments
不是真正的数组,开发人员往往要编写样板代码,把它
转换成数组。你或许仍然能见到这种用法,不过现在使用剩余参数可以省去很多麻烦。
剩余参数看起来像是展开运算符(
5.4
节),不过二者是互补关系。展开运
算符把一个数组或对象的属性展开为单个值,而剩余运算符收集单个值,把
它们插入一个数组对象。
6.4.4
参考
如果你想把一个数组中的值传给一个函数,而这个函数接受剩余参数,可以使用展
开运算符执行转换操作(见
5.4
节)。
这个示例使用循环处理数组中的值,不过你可以使
Array.reduce()
函数实现相
同的效果,而且更简洁,详见
5.18
节。
6.5
使用具名函数参数
6.5.1
问题
你想用一种更简单的方式选择传给函数的可选参数。
6.5.2
方案
把所有可选参数放在一个对象字面量(
7.2
节)中。调用方可以决定使用哪些可选参
数创建对象字面量。下面的示例使用这种模式调用一个函数。
函数
151
someFunction(arg1, arg2, {optionalArg1: val1, optionalArg2: val2});
在函数中,你可以使用析构赋值句法快速把值从对象字面量中复制出来 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.

Read now

Unlock full access

More than 5,000 organizations count on O’Reilly

AirBnbBlueOriginElectronic ArtsHomeDepotNasdaqRakutenTata Consultancy Services

QuotationMarkO’Reilly covers everything we've got, with content to help us build a world-class technology community, upgrade the capabilities and competencies of our teams, and improve overall team performance as well as their engagement.
Julian F.
Head of Cybersecurity
QuotationMarkI wanted to learn C and C++, but it didn't click for me until I picked up an O'Reilly book. When I went on the O’Reilly platform, I was astonished to find all the books there, plus live events and sandboxes so you could play around with the technology.
Addison B.
Field Engineer
QuotationMarkI’ve been on the O’Reilly platform for more than eight years. I use a couple of learning platforms, but I'm on O'Reilly more than anybody else. When you're there, you start learning. I'm never disappointed.
Amir M.
Data Platform Tech Lead
QuotationMarkI'm always learning. So when I got on to O'Reilly, I was like a kid in a candy store. There are playlists. There are answers. There's on-demand training. It's worth its weight in gold, in terms of what it allows me to do.
Mark W.
Embedded Software Engineer

You might also like

JavaScript Patterns

JavaScript Patterns

Stoyan Stefanov
JavaScript

JavaScript

David Flanagan
JavaScript

JavaScript

T. J. Crowder

Publisher Resources

ISBN: 9787519869601