是的,Array.map() 或 $.map() 做同样的事情。
//array.map:
var ids = this.fruits.map(function(v){
return v.Id;
});
//jQuery.map:
var ids2 = $.map(this.fruits, function (v){
return v.Id;
});
console.log(ids, ids2);
http://jsfiddle.net/NsCXJ/1/
由于旧浏览器不支持array.map,我建议你坚持使用jQuery方法。
如果您出于某种原因更喜欢另一个,您可以随时添加一个 polyfill 以支持旧浏览器。
您也可以随时向数组原型添加自定义方法:
Array.prototype.select = function(expr){
var arr = this;
//do custom stuff
return arr.map(expr); //or $.map(expr);
};
var ids = this.fruits.select(function(v){
return v.Id;
});
如果您传递字符串,则使用函数构造函数的扩展版本。也许可以玩的东西:
Array.prototype.select = function(expr){
var arr = this;
switch(typeof expr){
case 'function':
return $.map(arr, expr);
break;
case 'string':
try{
var func = new Function(expr.split('.')[0],
'return ' + expr + ';');
return $.map(arr, func);
}catch(e){
return null;
}
break;
default:
throw new ReferenceError('expr not defined or not supported');
break;
}
};
console.log(fruits.select('x.Id'));
http://jsfiddle.net/aL85j/
更新:
由于这已成为如此受欢迎的答案,因此我添加了类似的 where() + firstOrDefault()。这些也可以与基于字符串的函数构造方法一起使用(这是最快的),但这是另一种使用对象文字作为过滤器的方法:
Array.prototype.where = function (filter) {
var collection = this;
switch(typeof filter) {
case 'function':
return $.grep(collection, filter);
case 'object':
for(var property in filter) {
if(!filter.hasOwnProperty(property))
continue; // ignore inherited properties
collection = $.grep(collection, function (item) {
return item[property] === filter[property];
});
}
return collection.slice(0); // copy the array
// (in case of empty object filter)
default:
throw new TypeError('func must be either a' +
'function or an object of properties and values to filter by');
}
};
Array.prototype.firstOrDefault = function(func){
return this.where(func)[0] || null;
};
用法:
var persons = [{ name: 'foo', age: 1 }, { name: 'bar', age: 2 }];
// returns an array with one element:
var result1 = persons.where({ age: 1, name: 'foo' });
// returns the first matching item in the array, or null if no match
var result2 = persons.firstOrDefault({ age: 1, name: 'foo' });
这是一个jsperf test,用于比较函数构造函数与对象字面量的速度。如果您决定使用前者,请记住正确引用字符串。
我个人的偏好是在过滤1-2个属性时使用基于对象字面量的方案,并通过回调函数进行更复杂的过滤。
在向原生对象原型添加方法时,我将用 2 个一般提示来结束本文:
-
在覆盖之前检查现有方法的出现,例如:
if(!Array.prototype.where) {
Array.prototype.where = ...
如果您不需要支持 IE8 及以下版本,请使用 Object.defineProperty 定义方法,使其不可枚举。如果有人在数组上使用了for..in(这首先是错误的)
他们也将迭代可枚举的属性。请注意。