J'ai écrit deux méthodes Array qui, je pense, seront très utiles pour le travail que je fais. Modelé après les méthodes de tableau de Ruby, voici mes méthodes find et find_all. Je pensais juste que je les jetterais dans la communauté et que j'aurais des réactions. Je suis assez nouveau dans la programmation JS, je n'utilise probablement pas assez de mécanismes défensifs et peut-être qu'il y a des optimisations à faire. Des pensées?javascript function opinions
Array.prototype.find = function(attrs){
// If an object wasn't passed in return false, maybe throw format exception?
// or do primitive type search, but that's not really useful as you're passing in the very value you're looking for
if (typeof attrs != 'object'){
return false;
}else{
for(var i=0; i < this.length; i++){
if (typeof this[i] != 'object'){
return false;
}else{
var match = true;
// Loop through all attributes of the parameters object and test for existence and match
for(item in attrs){
match = match && (this[i][item] && (this[i][item] === attrs[item]));
}
if(match){
return this[i];
}
}
}
// default return if no items found
return false;
}
};
// find_all behaves similarly to find only returns all matched objects
// See ruby's find_all method on arrays
Array.prototype.find_all = function(attrs){
// If an object wasn't passed in return false, maybe throw format exception?
// or do primitive type search, but that's not really useful as you're passing in the very value you're looking for
if (typeof attrs != 'object'){
return false;
}else{
var valid_items = [];
for(var i=0; i < this.length; i++){
if (typeof this[i] != 'object'){
return false;
}else{
var match = true;
// Loop through all attributes of the parameters object and test for existence and match
for(item in attrs){
match = match && (this[i][item] && (this[i][item] === attrs[item]));
}
if(match){
valid_items.push(this[i]);
}
}
}
return valid_items;
}
}
Quelques exemples:
var a={id:1,parent_id:2}
var b={id:2,parent_id:3}
var c={id:3,parent_id:2}
var arr = [a,b,c]
arr.find({parent_id:2})
// Object id: 1 parent_id: 2
arr.find_all({parent_id:2})
// [Object id: 1 parent_id: 2, Object id: 3 parent_id: 2 ]
Ce type de question est mieux adapté pour http://www.refactormycode.com/ – ykaganovich