Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
264 views
in Technique[技术] by (71.8m points)

javascript - What is the meaning of "foo(...arg)" (three dots in a function call)?

Can someone tell what is "..." in the below code in the "Intro to Angular" example?

getHeroes() {
    this.backend.getAll(Hero).then( (heroes: Hero[]) => {
      this.logger.log(`Fetched ${heroes.length} heroes.`);
      this.heroes.push(...heroes); // fill cache
    });
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This has nothing to do with jQuery or Angular. It's a feature that was introduced in ES2015.

This particular use of ... doesn't actually have an official name. A name that is in line with other uses would be "spread argument" (a generic term would be "spread syntax"). It "explodes" (spreads) an iterable and passes each value as argument to the function. Your example is equivalent to:

this.heroes.push.apply(this.heroes, Array.from(heroes));

Besides being more concise, another advantage of ... here is that it can be more easily used with other concrete arguments:

func(first, second, ...theRest);

// as opposed to the following or something similar:
 func.apply(null, [first, second].concat(Array.from(heroes)));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...