jQuery的:在数组元素的指数,其中predicate [英] jQuery: Index of element in array where predicate

查看:196
本文介绍了jQuery的:在数组元素的指数,其中predicate的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有对象的数组。每个对象具有除其他外,一个ID属性。我想找对象的数组与特定的ID在索引中。是否有任何优雅而简洁的方式jQuery来做到这一点?

I have an array of objects. Each object has, among others, an ID attribute. I want to find the index in the array of the object with a specific ID. Is there any elegant and simple way to do this in jQuery?

推荐答案

在这种情况下,你应该在JavaScript中使用循环,而不是使用jQuery的。见路3 <一个href=\"http://net.tutsplus.com/tutorials/javascript-ajax/10-ways-to-instantly-increase-your-jquery-performance/\" rel=\"nofollow\">http://net.tutsplus.com/tutorials/javascript-ajax/10-ways-to-instantly-increase-your-jquery-performance/

In the case you should use for loop in javascript instead of using jQuery. See way 3 in http://net.tutsplus.com/tutorials/javascript-ajax/10-ways-to-instantly-increase-your-jquery-performance/

更新: jQuery是用JavaScript编写的,它不能比也用JavaScript编写的另一个code更快。 jQuery是非常好的,如果你使用DOM工作,但并没有真正帮助,如果你正在使用简单的JavaScript数组或对象的工作。

UPDATED: jQuery is written in javascript and it can not be faster than another code written also in javascript. jQuery is very good if you work with the DOM, but doesn't really help if you're working with simple javascript arrays or objects.

您正在寻找的code可以是这样的:

The code you're looking for can be something like this:

for (var i=0, l = ar.length; i<l; i++) {
    if (ar[i].ID === specificID) {
        // i is the index. You can use it here directly or make a break
        // and use i after the loop (variables in javascript declared
        // in a block can be used anywhere in the same function)
        break;
    }
}
if (i<l) {
    // i is the index
}

重要的是你应该持有一些简单的JavaScript的规则:始终声明局部变量(不要忘了 VAR 前变量声明)和缓存使用更多的任何属性或索引不是在一个局部变量(如 ar.length 以上)一次。 (例如,见 http://wiki.forum.nokia.com/index.php/JavaScript_Performance_Best_Practices

Important that you should hold some simple javascript rules: Always declare local variables (don't forget var before variable declaration) and cache any properties or indexes that you use more than one time in a local variable (like ar.length above). (See for example http://wiki.forum.nokia.com/index.php/JavaScript_Performance_Best_Practices)

这篇关于jQuery的:在数组元素的指数,其中predicate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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