admin管理员组文章数量:1287582
I'm trying to decide whether to use the reduce() method in Javascript for a function I need to write which is something like this
var x = [some array], y = {};
for (...) {
someOperation(x[i]);
y[x[i]] = "some other value";
}
Now this can obviously be written as a reduce() function in the following manner:
x.reduce(function(prev, current, index, arr) {
someOperation(current);
prev[current] = "some other value";
return prev;
}, {})
Or something like that. Is there any performance or other difference between the two? Or some other reason (like browser support, for instance) due to which one should be favoured over the other in a web programming environment? Thanks.
I'm trying to decide whether to use the reduce() method in Javascript for a function I need to write which is something like this
var x = [some array], y = {};
for (...) {
someOperation(x[i]);
y[x[i]] = "some other value";
}
Now this can obviously be written as a reduce() function in the following manner:
x.reduce(function(prev, current, index, arr) {
someOperation(current);
prev[current] = "some other value";
return prev;
}, {})
Or something like that. Is there any performance or other difference between the two? Or some other reason (like browser support, for instance) due to which one should be favoured over the other in a web programming environment? Thanks.
Share Improve this question asked Jun 16, 2011 at 1:17 JayJay 3,5314 gold badges37 silver badges52 bronze badges4 Answers
Reset to default 4Even though I prefer these operations (reduce, map, filter, etc.), it's still not feasible to use them because of certain browsers that do not support them in their implementations. Sure, you can "patch" it by extending the Array
prototype, but that's opening a can of worms too.
I don't think there's anything inherently wrong with these functions, and I think they make for better code, but for now it's best not to use them. Once a higher percentage of the population uses a browser that supports these functions I think they'll be fair game.
As far as performance, these will probably be slower than hand written for loops because of the overhead from function calls.
map
and filter
and reduce
and forEach
and ... (more info: https://developer.mozilla/en/JavaScript/Reference/Global_Objects/Array#Iteration_methods ) are far better than normal loops because:
- They are more elegant
- They encourage functional programming (see benefits of functional programming)
- You will need to write functions anyway and pass into them, as parameters, iteration variables. This is because javascript has no block scope. Functions like
map
andreduce
make your job so much easier because they automatically set up your iteration variable and pass it into your function for you.
IE9 claims to support these. They're in the official javascript/ecmascript spec. If you care about people who are using IE8, that is your prerogative. If you really care, you can hack it by overriding Array.prototype
for ONLY IE8 and older, to "fix" IE8 and older.
reduce is used to return one value from an array, as a result of sequentially processing the results of the previous elements.
reduceRight does the same, but starts at the end and works backwards.
map is used to return an array whose members have all been passed through a function.
neither method affects the array itself.
var A1= ['1', '2', '3', '4', '5', '6', '7',' 8'];
// This use of map returns a new array of the original elements, converted to numbers-
A1=A1.map(Number); // >> each of A1's elements converted to a number
// This reduce totals the array elements-
var A1sum= A1.reduce(function(a, b){ return a+b;});
// A1sum>> returned value: (Number) 36
They are not supported in older browsers, so you'll need to provide a substitute for them. Not worth it if all you are doing can be replicated in a simple loop.
Figuring the standard deviation of a population is an example where both map and reduce can be effectively used-
Math.mean= function(array){
return array.reduce(function(a, b){ return a+b; })/array.length;
}
Math.stDeviation=function(array){
var mean= Math.mean(array);
dev= array.map(function(itm){return (itm-mean)*(itm-mean); });
return Math.sqrt(dev.reduce(function(a, b){ return a+b; })/array.length);
}
var A2= [6.2, 5, 4.5, 6, 6, 6.9, 6.4, 7.5];
alert ('mean: '+Math.mean(A2)+'; deviation: '+Math.stDeviation(A2))
kennebec - good going, but your stDeviation function calls reduce twice and map once when it only needs a single call to reduce (which makes it a lot faster):
Math.stDev = function (a) {
var n = a.length;
var v = a.reduce(function (v, x) {
v[0] += x * x;
v[1] += x;
return v;
}, [0,0]);
return Math.sqrt( (v[0] - v[1]*v[1] / n) / n );
}
Should do a conversion to number when assigning to v[1] to make sure string numbers don't mess with the result and the divisor in the last line should probablly be (n - 1) in most cases, but that's up to the OP. :-)
本文标签: web applicationsWhat are the advantages of Javascript39s reduce() function (and map())Stack Overflow
版权声明:本文标题:web applications - What are the advantages of Javascript's reduce() function? (and map()) - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741268454a2368891.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论