是的,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个属性时使用基于对象字面值的解决方案,并为更复杂的过滤传递回调函数。
if(!Array.prototype.where) { Array.prototype.where = ...
如果您:覆盖如之前
检查的现有方法发生:
我会添加方法原生对象原型,用时2个一般提示结束这不需要支持IE8及以下版本,请使用Object.defineProperty定义方法,使它们不可枚举。如果有人在数组上使用了for..in
(这首先是错误的) 它们也会迭代枚举属性。只是一个头。
@ChrisNevill我添加了一个字符串版本,以防万一你intrested – Johan
@MUlferts良好的捕获,更新:)。现在我建议使用lodash来完成这些任务。他们公开了与上面的代码相同的接口 – Johan
为了支持knockout observables:'return typeof item [property] ==='function'? item [property]()=== filter [property]:item [property] === filter [property];' –