【问题标题】:call function on javascript array only if it exists, return empty array otherwise仅当 JavaScript 数组存在时才调用函数,否则返回空数组
【发布时间】:2016-10-27 03:43:04
【问题描述】:

在 Javascript (ES6) 中,仅当数组存在时才在数组上运行方法(例如“排序”),否则返回一个空数组,什么是好的(简洁)方式?

例如在这个例子中,“this.props.items”可以是未定义的,我不希望它因“无法读取未定义的属性'排序'”而失败:

const sortedItems = this.props.items.sort((a, b) => a.id - b.id);

【问题讨论】:

  • (this.props.items || []).sort(...

标签: javascript


【解决方案1】:

const sortedItems = this.props.items ? this.props.items.sort() : []

与 Tushar 基本相同,但没有不必要的排序。

【讨论】:

  • 每个不必要的排序可能需要不到一微秒的时间。
猜你喜欢
  • 1970-01-01
  • 2023-01-09
  • 1970-01-01
  • 2022-12-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-20
相关资源
最近更新 更多