Yes, Array.map() or $.map() does the same thing.
//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/个
从数组开始.map在旧浏览器中不受支持,我建议您坚持使用jQuery方法.
If you prefer the other one for some reason you could always add a polyfill for old browser support.
You can always add custom methods to the array prototype as well:
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;
});
An extended version that uses the function constructor if you pass a string. Something to play around with perhaps:
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/
Update:
既然这已经成为一个很受欢迎的答案,我添加了类似的我的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;
};
Usage:
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' });
Here is a jsperf test to compare the function constructor vs object literal speed. If you decide to use the former, keep in mind to quote strings correctly.
My personal preference is to use the object literal based solutions when filtering 1-2 properties, and pass a callback function for more complex filtering.
在将方法添加到本机对象原型时,我将用两个一般提示来结束本文:
在覆盖之前判断现有方法的出现情况,例如:
if(!Array.prototype.where) {
Array.prototype.where = ...
个
如果不需要支持IE8及以下版本,请使用Object.defineProperty定义方法,使其不可枚举.如果有人在数组上使用for..in
(这首先是错误的)