Array.filter 与 $filter('filter') [英] Array.filter vs $filter('filter')

查看:28
本文介绍了Array.filter 与 $filter('filter')的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我应该在 Angular 应用中使用哪个,为什么?

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.

更新:

幕后 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);

这篇关于Array.filter 与 $filter('filter')的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆