Given I have an array of "purpose" objects:

//array of purpose objects:
var purposeObjects = [
    {purpose: "daily"},
    {purpose: "weekly"},
    {purpose: "monthly"}
];

(为简单起见,我省略了其他属性)

现在,我希望有一个方法,如果找到匹配的目的名称,它将返回一个特定的对象.

这是行不通的:

function findPurpose(purposeName){
    return $.grep(purposeObjects, function(){
      return this.purpose == purposeName;
    });
};

findPurpose("daily");

但它实际上返回一个空数组:

[]

我使用的是JQuery 1.5.2.我也try 过美元.但是没有运气.

关于如何实现这一点有什么 idea 吗?

推荐答案

The error was that you cannot use this in the grep, but you must use a reference to the element. This works:

function findPurpose(purposeName){
    return $.grep(purposeObjects, function(n, i){
      return n.purpose == purposeName;
    });
};

findPurpose("daily");

returns:

[Object { purpose="daily"}]

Jquery相关问答推荐

在shiny 的datatable列中启用智能搜索

将搜索面板和服务器端与POST AJAX请求一起使用时出现DataTables错误

Django BaseDataTableView-Filter_queryset方法不起作用

在添加_renderMenu方法时,是什么原因导致jQuery UI AutoComplete抛出TypeError?

在 Laravel 中使用 jQuery post 按相关值过滤 Select 选项,如何显示从控制器返回的数据?

为什么对同一个 ASP.NET MVC 操作的多个同时 AJAX 调用会导致浏览器阻塞?

jQuery ajax 调用默认超时值

如何使用 jQuery 重置 Select 元素

不使用插件的 jQuery 缓动函数

Ajax 更新后在 jQuery 中重新绑定事件(更新面板)

在没有 jQuery 的情况下在 node.js 上合并或合并 JSON

如何获取 onclick 调用对象?

jQuery.extend 和 jQuery.fn.extend 的区别?

addClass - 可以在同一个 div 上添加多个类吗?

jQuery:如何找到第一个可见的输入/ Select /文本区域,不包括按钮?

Url.Action 在我的 url 中放了一个 &,我该如何解决这个问题?

Uncaught TypeError: undefined is not a function on loading jquery-min.js

javascript,是否有像 isArray 这样的 isObject 函数?

使用javascript将HTML页面中的div下载为pdf

Drop 事件未在 chrome 中触发