且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Array.filter 与 $filter('filter')

更新时间:2023-12-04 11:30:52

关键区别在于 $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.

更新:

幕后 angular 使用 Array.prototype.filter:

Under the hood angular uses the 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);