似乎filter()和filterProperty()非常相似,它们都是Enumerable函数,它们返回过滤后的数组。
在什么情况下应该使用其中一个?
最佳答案
更新: 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 example
关于ember.js - Emberjs filter()与filterProperty(),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16924962/