【问题标题】:What is the Underscore for in front of the arrow function (_=>) in the hero.service.ts Angular v5 Tour of Heroes Tutorial?hero.service.ts Angular v5 Tour of Heroes 教程中箭头函数(_=>)前面的下划线是什么?
【发布时间】:2018-06-04 18:20:57
【问题描述】:

我遇到了打字稿或 javascript 语法问题。 谁能告诉我 _ => this.log... 是什么意思?

我习惯于看到一个名称参数被传递到那里的箭头函数。

它只是意味着“无参数”吗?

参考:https://angular.io/tutorial/toh-pt6#add-heroserviceupdatehero

    /** PUT: update the hero on the server */
updateHero (hero: Hero): Observable<any> {
  return this.http.put(this.heroesUrl, hero, httpOptions).pipe(
    tap(_ => this.log(`updated hero id=${hero.id}`)),
    catchError(this.handleError<any>('updateHero'))
  );
}

【问题讨论】:

标签: javascript angularjs typescript angular-services


【解决方案1】:

() =&gt; {console.log('Hello World')}

 _ =&gt; {console.log('Hello World')}

如果你的函数不需要参数,上述两种方法都是一样的。

下划线_ 只是一个一次性变量,这意味着它可以是任何变量名,因为它永远不会被使用。只是他们通常用下划线表示函数不需要参数。

我使用()=&gt; 编写不带参数的函数,但我见过很多使用下划线的版本,因此最好了解两者。

【讨论】:

    【解决方案2】:

    命名一个不会在函数中使用的参数只是一个概念。

    相反,他们会这样写:

    tap(() => this.log(`updated hero id=${hero.id}`)),
    

    如果您想了解更多信息,this post 是一个好的开始。

    【讨论】:

    • 我现在明白了。知道为什么我们不能写:tap(this.log(updated hero id=${hero.id}),
    • @OpTechMarketing 因为tap 期望调用函数,而不是返回值。
    猜你喜欢
    • 1970-01-01
    • 2022-11-21
    • 2020-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-04
    • 2016-03-25
    • 2017-05-08
    相关资源
    最近更新 更多