If you want it to be fast, you'll want a for
loop so that you can break the loop when the match is found.
var result;
for( var i = 0, len = selected_products.length; i < len; i++ ) {
if( selected_products[i][0] === 'r1' ) {
result = selected_products[i];
break;
}
}
Of course this assumes there's only one match.
If there's more than one, then you could use $.grep
if you want jQuery:
var result = $.grep(selected_products, function(v,i) {
return v[0] === 'r1';
});
This will give you a new Array that is a subset of the matched items.
In a similar manner, you could use Array.prototype.filter
, if you only support modern JavaScript environments.
var result = selected_products.filter(function(v,i) {
return v[0] === 'r1';
});
One other solution would be to create an object where the keys are the rn
items. This should give you a very fast lookup table.
var r_table = {};
for( var i = 0, len = selected_products.length; i < len; i++ ) {
r_table[selected_products[i][0]] = selected_products[i];
}
Then do your lookups like this:
r_table.r4;
Again this assumes that there are no duplicate rn
items.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…