Array.filter vs $ filter('filter') [英] Array.filter vs $filter('filter')
问题描述
我应该在角度应用程序中使用哪个?为什么?
Which one should i use in an angular app and why?
array.filter(o => o.name === myName);
或
$filter('filter')(array, {name: myName}, true);
推荐答案
主要区别在于$filter('filter')
提供的快捷方式或语法糖.例如,以下语法可用于在项目的任何string
属性中获取包含keyword
字符串的项目:
The key difference is the shortcuts or syntactic sugar provided by the $filter('filter')
. For example, the following syntax can be used to get the items containing the keyword
string in any of the item's string
properties:
$filter('filter')(array, 'keyword')
使用标准ES5 Array.prototype.filter
不能如此简单.
Which can not be as simple using the standard ES5 Array.prototype.filter
.
两种方法的总体思路相同-将给定数组的子集作为 NEW 数组返回.
Whereas the general idea is the same for both approaches - to return a subset of a given array as a NEW array.
更新:
内幕角使用Array.prototype.filter
:
function filterFilter() {
// predicateFn is created here...
return Array.prototype.filter.call(array, predicateFn);
}
因此,如果您不使用快捷方式-angular只需将呼叫委派给标准filter
.
So, if you don't use the shortcuts - angular simply delegates the call to the standard filter
.
要回答您的问题:使用可减少代码编写的代码.在您的特定情况下,它是array.filter(o => o.name === myName);
To answer your question: use the one that lets you write less code. In your particular case it would be array.filter(o => o.name === myName);
这篇关于Array.filter vs $ filter('filter')的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!