2010-07-13 19 views

Respuesta

4

En este caso, debe usar el bucle for en javascript en lugar de usar jQuery. Ver 3 en forma http://net.tutsplus.com/tutorials/javascript-ajax/10-ways-to-instantly-increase-your-jquery-performance/

Actualizado: jQuery está escrito en javascript y no puede ser más rápido que otro código escrito también en javascript. jQuery es muy bueno si trabajas con el DOM, pero realmente no ayuda si trabajas con matrices u objetos javascript simples.

El código que está buscando puede ser algo como esto:

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 
} 

importante que se debe mantener algunas reglas simples javascript: Siempre declarar variables locales (no se olvide var antes de la declaración de variables) y caché cualquier propiedad o índice que use más de una vez en una variable local (como ar.length arriba). (Véase, por ejemplo http://wiki.forum.nokia.com/index.php/JavaScript_Performance_Best_Practices)

3

En realidad, no elegante, pero un truco lindo:

var index = parseInt(
    $.map(array, function(i, o) { return o.id === target ? i : ''; }).join('') 
); 

jQuery no tiene una gran cantidad de construcciones funcionales como esa; la filosofía de la biblioteca está realmente centrada en el trabajo de las disputas de DOM. Ni siquiera agregarán una función .reduce() porque nadie puede pensar en una razón por la que sería útil para la funcionalidad principal.

La biblioteca Underscore.js tiene muchas de esas instalaciones, y "funciona bien" con jQuery.

+0

bueno, pero ineficiente, ya que pasa por todos los elementos de la matriz ... Si los revisas, puedes construir un hash inverso para que puedas responder la Q por muchos "specificID" s. – epeleg

+0

@epeleg bien sí, claramente. – Pointy

5
 
See [`Array.filter`][1] to filter an array with a callback function. Each object in the array will be passed to the callback function one by one. The callback function must return `true` if the value is to be included, or false if not. 

    var matchingIDs = objects.filter(function(o) { 
     return o.ID == searchTerm; 
    }); 

All objects having the ID as searchTerm will be returned as an array to matchingIDs. Get the matching element from the first index (assuming ID is unique and there's only gonna be one) 

    matchingIDs[0]; 

    [1]: https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/filter 

Actualización:

Pedido findIndex de ECMAScript 6.

items.findIndex(function(item) { item.property == valueToSearch; }); 

Desde findIndex aún no está disponible en la mayoría de los navegadores, se puede rellenar usando este implementation:

if (!Array.prototype.findIndex) { 
    Array.prototype.findIndex = function(predicate) { 
    if (this == null) { 
     throw new TypeError('Array.prototype.findIndex called on null or undefined'); 
    } 
    if (typeof predicate !== 'function') { 
     throw new TypeError('predicate must be a function'); 
    } 
    var list = Object(this); 
    var length = list.length >>> 0; 
    var thisArg = arguments[1]; 
    var value; 

    for (var i = 0; i < length; i++) { 
     value = list[i]; 
     if (predicate.call(thisArg, value, i, list)) { 
     return i; 
     } 
    } 
    return -1; 
    }; 
} 
+2

El OP preguntó cómo obtener el índice del elemento, no el elemento en sí. – epeleg

+0

@epeleg - No he leído la pregunta correctamente, parece. Pasar por cada objeto y romper cuando se encuentra una coincidencia es el camino a seguir, como sugirió Oleg. – Anurag

0

Use jOrder. http://github.com/danstocker/jorder

Introduzca su matriz en una tabla jOrder y agregue un índice en el campo 'ID'.

var table = jOrder(data) 
    .index('id', ['ID']); 

A continuación, obtener el índice de matriz de un elemento por:

var arrayidx = table.index('id').lookup([{ ID: MyID }]); 

Si desea toda la fila, entonces:

var filtered = table.where([{ ID: MyID }]); 

Voila.

1

No hay métodos incorporados para esto; el método [].indexOf() no toma un predicado, por lo que necesita algo de encargo:

function indexOf(array, predicate) 
{ 
    for (var i = 0, n = array.length; i != n; ++i) { 
     if (predicate(array[i])) { 
      return i; 
     } 
    } 
    return -1; 
} 

var index = indexOf(arr, function(item) { 
    return item.ID == 'foo'; 
}); 

La función devuelve -1 si el predicado nunca cede un valor Truthy.

Cuestiones relacionadas