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; } ?>javascript - Implementing reduce() from scratch, not sure how JS knows what "array" is - Stack Overflow
最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Implementing reduce() from scratch, not sure how JS knows what "array" is - Stack Overflow

programmeradmin3浏览0评论

I'm trying to implement reduce() from scratch. I was able to get it working, but how does javascript know what "array" is even though I never defined it anywhere?

function reduce(callback, initialVal) {
  var accumulator = (initialVal === undefined) ? undefined : initialVal;
  for (var i=0; i<array.length; i++) {
    if (accumulator !== undefined) {
      accumulator = callback(accumulator, array[i], i, array);
    } else {
      accumulator = array[i]
    }
  }
  return accumulator;
};

// testing a basic sum
arr = [1,2,3]
arr.reduce( (accumulator, elem) => accumulator+=elem )

EDIT: I got it working :D I Changed 'array' to "this" since I was creating a new method under Array.prototype.

Array.prototype.myReduce = function(callback, initialVal) {
  var accumulator = (initialVal !== undefined) ? initialVal : undefined;
  for (var i=0; i<this.length; i++) {
    if (accumulator !== undefined) {
      accumulator = callback(accumulator, this[i], i, this);
    } else {
      accumulator = this[i]
    }
  }
  return accumulator;
};

arr.myReduce( (accumulator, elem) => accumulator+=elem )
arr.myReduce( (accumulator, elem) => accumulator+=elem , 100)

I'm trying to implement reduce() from scratch. I was able to get it working, but how does javascript know what "array" is even though I never defined it anywhere?

function reduce(callback, initialVal) {
  var accumulator = (initialVal === undefined) ? undefined : initialVal;
  for (var i=0; i<array.length; i++) {
    if (accumulator !== undefined) {
      accumulator = callback(accumulator, array[i], i, array);
    } else {
      accumulator = array[i]
    }
  }
  return accumulator;
};

// testing a basic sum
arr = [1,2,3]
arr.reduce( (accumulator, elem) => accumulator+=elem )

EDIT: I got it working :D I Changed 'array' to "this" since I was creating a new method under Array.prototype.

Array.prototype.myReduce = function(callback, initialVal) {
  var accumulator = (initialVal !== undefined) ? initialVal : undefined;
  for (var i=0; i<this.length; i++) {
    if (accumulator !== undefined) {
      accumulator = callback(accumulator, this[i], i, this);
    } else {
      accumulator = this[i]
    }
  }
  return accumulator;
};

arr.myReduce( (accumulator, elem) => accumulator+=elem )
arr.myReduce( (accumulator, elem) => accumulator+=elem , 100)
Share Improve this question edited Apr 16, 2019 at 3:23 tbd_ asked Apr 16, 2019 at 2:49 tbd_tbd_ 1,2682 gold badges20 silver badges46 bronze badges 5
  • you need to create array.prototype.And also array.reduce overwrite the default js is bad practise.its affected the library of you are included.Better use different name instead js default – prasanth Commented Apr 16, 2019 at 2:51
  • Are you sure YOUR code is getting called and not built in reduce that is on Array's prototype? – JohanP Commented Apr 16, 2019 at 2:51
  • [ and ] tells JS that it's an array – Anand G Commented Apr 16, 2019 at 2:51
  • Possible duplicate of adding custom functions into Array.prototype – prasanth Commented Apr 16, 2019 at 2:55
  • 1 @prasanth you guys are right, it's most likely calling the native reduce() and not the one I just created...if I change the function to "myReduce()" it throws the error "TypeError: arr.myReduce is not a function". I'll retry by creating it under Array.prototype! – tbd_ Commented Apr 16, 2019 at 3:04
Add a ment  | 

2 Answers 2

Reset to default 16

You are pretty close. The one insight that seems to be missing is that inside your function, this will be defined as the array your function was called on. So you can use this in the places you're currently using array, which in your function will be undefined (as you suspected). You probably also want to start the loop in a different place depending on whether the initial value was passed in. For example:

function reduce(callback, initialVal) {
    var accumulator = ( initialVal === undefined) ? this[0] : initialVal;
    var start = (initialVal === undefined) ? 1 : 0
    for (var i = start; i < this.length; i++) {
        accumulator = callback(accumulator, this[i])
    }
    return accumulator;
  };

Array.prototype.myReduce = reduce

// no init value
console.log([1, 2, 3].myReduce((sum, curr) => sum + curr))

// init value:
console.log([1, 2, 3].myReduce((sum, curr) => sum + curr, 1000))

Crips and clear

Array.prototype.myReduce = function (callback, iterator) {
    // Initialize the iterator based on the type of the first element
    if (typeof this[0] === "number" && iterator === undefined) {
        iterator = 0;
    } else if (typeof this[0] === "string" && iterator === undefined) {
        iterator = "";
    }

    // Iterate through the array and apply the callback
    for (let i = 0; i < this.length; i++) {
        iterator = callback(iterator, this[i]);
    }

    return iterator; // Return the final accumulated value
};

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论