19

看起来filter()filterProperty()非常相似,都是返回过滤数组的 Enumerable 函数。

在什么情况下我应该使用其中一种?

4

1 回答 1

34

更新: filterProperty()已替换为filterBy(). 用法相同,请参阅下面的评论。

filterBy()是一种快捷方式filter(),可让您根据可枚举元素的指定属性快速过滤可枚举。如果filter()您需要在无法使用filterBy().

例如,假设您有一个这样的对象数组:

[
  {firstName: 'Kris', lastName: 'Selden'},
  {firstName: 'Luke', lastName: 'Melia'},
  {firstName: 'Formerly Alex', lastName: 'Matchneer'}
]

并且您希望拥有一个计算属性,该属性使用过滤数组来仅包含以下人员firstName == 'Luke'

使用filter()

filterComputed: function() {
  return this.get('content').filter(function(item, index, enumerable){
    return item.firstName == 'Luke';
  });
}.property('content.@each')

使用filterBy()

filterByComputed: function() {
  return this.get('content').filterBy('firstName', 'Luke');
}.property('content.@each')

JSBin 示例

于 2013-06-04T19:11:31.387 回答