te')); return $arr; } /* 遍历用户所有主题 * @param $uid 用户ID * @param int $page 页数 * @param int $pagesize 每页记录条数 * @param bool $desc 排序方式 TRUE降序 FALSE升序 * @param string $key 返回的数组用那一列的值作为 key * @param array $col 查询哪些列 */ function thread_tid_find_by_uid($uid, $page = 1, $pagesize = 1000, $desc = TRUE, $key = 'tid', $col = array()) { if (empty($uid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('uid' => $uid), array('tid' => $orderby), $page, $pagesize, $key, $col); return $arr; } // 遍历栏目下tid 支持数组 $fid = array(1,2,3) function thread_tid_find_by_fid($fid, $page = 1, $pagesize = 1000, $desc = TRUE) { if (empty($fid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('fid' => $fid), array('tid' => $orderby), $page, $pagesize, 'tid', array('tid', 'verify_date')); return $arr; } function thread_tid_delete($tid) { if (empty($tid)) return FALSE; $r = thread_tid__delete(array('tid' => $tid)); return $r; } function thread_tid_count() { $n = thread_tid__count(); return $n; } // 统计用户主题数 大数量下严谨使用非主键统计 function thread_uid_count($uid) { $n = thread_tid__count(array('uid' => $uid)); return $n; } // 统计栏目主题数 大数量下严谨使用非主键统计 function thread_fid_count($fid) { $n = thread_tid__count(array('fid' => $fid)); return $n; } ?>Understanding Eloquent Javascript's Reduce function - Stack Overflow
最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Understanding Eloquent Javascript's Reduce function - Stack Overflow

programmeradmin3浏览0评论

In Eloquent Javascript, the author asks the reader to write a function countZeroes, which takes an array of numbers as its argument and returns the amount of zeroes that occur in it as another example for the use of the reduce function.

I know

  • that the concept of the reduce function is to take an array and turn it to a single value.
  • what the ternary operator is doing which is the essential portion of the function.

I don't know

  • where the arguments for the counter function are ing from.

From the book:

function countZeroes(array) {
  function counter(total, element) { // Where are the parameter values ing from?
    return total + (element === 0 ? 1 : 0);
  }
  return reduce(counter, 0, array);
}

Earlier example from the text:

function reduce(bine, base, array) {
 forEach(array, function (element) {
    base = bine(base, element);
  });
  return base;
}

In Eloquent Javascript, the author asks the reader to write a function countZeroes, which takes an array of numbers as its argument and returns the amount of zeroes that occur in it as another example for the use of the reduce function.

I know

  • that the concept of the reduce function is to take an array and turn it to a single value.
  • what the ternary operator is doing which is the essential portion of the function.

I don't know

  • where the arguments for the counter function are ing from.

From the book:

function countZeroes(array) {
  function counter(total, element) { // Where are the parameter values ing from?
    return total + (element === 0 ? 1 : 0);
  }
  return reduce(counter, 0, array);
}

Earlier example from the text:

function reduce(bine, base, array) {
 forEach(array, function (element) {
    base = bine(base, element);
  });
  return base;
}
Share Improve this question edited Nov 2, 2012 at 22:38 phant0m 16.9k6 gold badges51 silver badges84 bronze badges asked Nov 2, 2012 at 21:49 KMcAKMcA 1,2131 gold badge12 silver badges21 bronze badges 1
  • I've written a course on Codeacademy on this topic. It teaches the basics of higher value functions such as map, reduce, sort etc. codecademy./courses/javascript-advanced-en-eQcHT/0/1 – Christian Landgren Commented Jul 18, 2015 at 21:01
Add a ment  | 

3 Answers 3

Reset to default 8

the function counter is passed as the first parameter of reduce when called in your first block of code. Within the reduce function, the first parameter is known as bine. This is then called with parameters base and element which are the mysterious arguments you are seeking!

So the tricky bit, is that the function is not executed where it is defined and named, but passed as a parameter to the reduce function, which then executes it.

Edit: elaboration

so... the function is defined and named (at point 1), then the definition is passed, without the name to another function (at point 2) along with variables (I called i and ii) where it picks up the name of the first parameter (at point 3) before being called (at point 4) along with the other parameters

edit: further elaboration

I updated the image, to better explain the elements ing from the array.

So i is easier to follow, being created as 0 when the reduce function is called, and allocated the name base as a parameter, before being reassigned as the result of the counter/bine function, which returns the base with a possible increment.

ii starts life as an array passed to countZeroes, and is then passed along the chain until it is iterated over by a forEach loop, which extracts a single element and operates the bine function on it (along with base).

Looking at the code, there is only one possible answer: Since you the function counter is only referenced once when passed to reduce(), reduce must thus provide the arguments to the function.

How reduce works

Here is a visualization of how reduce works. You need to read the diagrom from top to bottom, / and \ denote which parameters (below) are passed to the counter() function above.

                   return value of reduce()
                   /
                 etc ...
                /
            counter
           /       \
       counter      xs[2]
      /       \
  counter      xs[1]
 /       \
0         xs[0]

counter() is initially provided with 0 (after all, the initial total amount of seen zeroes when you haven't processed any elements yet is just zero) and the first element.

That 0 is increased by one if the first element of the array is a zero. The new total after having seen the first element is then returned by counter(0, xs[0]) to the reduce() function. As long as elements are left, it then passes this value as new pending total to the counter() function, along with the next element from your array: xs[1].

This process is repeated as long as there are elements in the array.

Mapping this concept to the code

function reduce(bine, base, array) {
 forEach(array, function (element) {
    base = bine(base, element);
  });
  return base;
}

As can be seen in the illustration, 0 is passed through base to the function initially, along with element, which denotes xs[0] on the first "iteration" within the forEach construct. The resulting value is then written back to base.

As you can see in the visualization, 0 is the left parameter to the function counter(), whose result is then passed as left parameter to counter(). Since base/total acts as the left paramter within the forEach construct, it makes sense to write that value back to base/total, so the previous result will be passed to counter()/bine() again upon the next iteration. The path of /s is the "flow" of base/total.

Where element es from

From chapter 6 of Eloquent JavaScript, here is the implementation of forEach() (In the ment, I have substituted the call to action with the eventual values.)

function forEach(array, action) {
  for (var i = 0; i < array.length; i++)
    action(array[i]); // <-- READ AS: base = counter(base, array[i]);
}

action denotes a function, that is called within a simple for loop for every element, while iterating over array.

In your case, this is passed as action to forEach():

function (element) {
    base = bine(base, element);
}

It is the anonymous function defined upon each call to reduce(). So element is "really" array[i] once for each iteration of the for.

The reduce method passes the parameters in. Somewhere in the source code of the reduce function is probably something like this:

function reduce(iterator, memo, collection) { // in your example, iterator here is your counter function
    …
    // while looping through the collection you passed in
    memo = iterator(memo, collection[i], i); // it calls your counter function and
                                             // passes the total and the current array
                                             // element as well as the current index,
                                             // then stores the result to be passed in
                                             // with the next array element
    …
    return memo;
}

Addendum

Maybe this will help illustrate better (jsfiddle):

// very simple reduce implementation
function reduce(iterator, memo, collection) {
    for (var i = 0; i < collection.length; i++) {
        memo = iterator(memo, collection[i], i);
    }
    return memo;
}

zeroes = [1,0,0,1,1,0,1];
function counter(total, element) { return total + (element === 0 ? 1 : 0); }

alert(reduce(counter, 0, zeroes));
发布评论

评论列表(0)

  1. 暂无评论