简体   繁体   English

Javascript的reduce()函数有哪些优点? (和map())

[英]What are the advantages of Javascript's reduce() function? (and map())

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 我正在尝试决定是否在Javascript中使用reduce()方法来处理我需要编写的函数,这是类似的东西

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: 现在这可以通过以下方式写成reduce()函数:

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? 或者其他一些原因(例如浏览器支持),因为在Web编程环境中哪一个应该优先于另一个? Thanks. 谢谢。

Even 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. 当然,你可以通过扩展Array原型来“修补”它,但这也是一堆蠕虫。

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.org/en/JavaScript/Reference/Global_Objects/Array#Iteration_methods ) are far better than normal loops because: mapfilterreduce以及forEach和...(更多信息: https//developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array#Iteration_methods )远远优于普通循环,因为:

  1. They are more elegant 它们更优雅
  2. They encourage functional programming (see benefits of functional programming) 他们鼓励函数式编程(参见函数式编程的好处)
  3. You will need to write functions anyway and pass into them, as parameters, iteration variables. 你需要这么写的功能,并通过放进去,作为参数,迭代变量。 This is because javascript has no block scope. 这是因为javascript没有块范围。 Functions like map and reduce make your job so much easier because they automatically set up your iteration variable and pass it into your function for you. mapreduce等函数使您的工作变得更加容易,因为它们会自动设置迭代变量并将其传递给您的函数。

IE9 claims to support these. IE9声称支持这些。 They're in the official javascript/ecmascript spec. 他们是官方的javascript / ecmascript规范。 If you care about people who are using IE8, that is your prerogative. 如果你关心使用IE8的人,这是你的特权。 If you really care, you can hack it by overriding Array.prototype for ONLY IE8 and older, to "fix" IE8 and older. 如果你真的在乎,你可以通过覆盖只有IE8及更旧版本的Array.prototype来破解它,以“修复”IE8及更旧版本。

reduce is used to return one value from an array, as a result of sequentially processing the results of the previous elements. reduce用于从数组返回一个值,作为顺序处理前一个元素的结果的结果。

reduceRight does the same, but starts at the end and works backwards. reduceRight做同样的事情,但从最后开始并向后工作。

map is used to return an array whose members have all been passed through a function. map用于返回其成员全部通过函数传递的数组。

neither method affects the array itself. 这两种方法都不会影响数组本身

var A1= ['1', '2', '3', '4', '5', '6', '7',' 8']; 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- //这个map的使用返回原始元素的新数组,转换为数字 -

A1=A1.map(Number); A1 = A1.map(数量); // >> each of A1's elements converted to a number // >> A1的每个元素都转换为数字

// This reduce totals the array elements- //这减少了数组元素 -

var A1sum= A1.reduce(function(a, b){ return a+b;}); var A1sum = A1.reduce(function(a,b){return a + b;});

// A1sum>> returned value: (Number) 36 // A1sum >>返回值:(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): kennebec - 很好,但你的stDeviation函数调用reduce两次并映射一次只需要一次调用reduce (这使得它快得多):

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. 在分配给v [1]时应该转换为数字以确保字符串数字不会与结果混淆,并且在大多数情况下最后一行中的除数可能是(n-1),但这取决于OP 。 :-) :-)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM