JS常用的数组方法总结(二)

本文详细介绍了JavaScript数组的reduce方法,包括函数参数、源码解析、参数分析、示例及常见使用场景,如计算总价、统计元素出现次数、数组去重、按属性分类等。还展示了如何使用reduce来根据课程不同部分的分数计算总成绩。
摘要由CSDN通过智能技术生成

Array.prototype.reduce()

目录

Array.prototype.reduce()

函数参数:

源码:

参数分析

 示例

一些使用场景


函数参数:

arr.reduce(callback(accumulator, currentValue[, index[, array]])[, initialValue])

源码:

V8源码1223行

function ArrayReduce(callback, current) {
  CHECK_OBJECT_COERCIBLE(this, "Array.prototype.reduce");

  // Pull out the length so that modifications to the length in the
  // loop will not affect the looping and side effects are visible.
  var array = TO_OBJECT(this);
  var length = TO_LENGTH(array.length);
  return InnerArrayReduce(callback, current, array, length,
                          arguments.length);
}

function InnerArrayReduce(callback, current, array, length, argumentsLength) {
    // 判断传入的函数是否能被调用
  if (!IS_CALLABLE(callback)) {
      
    throw %make_type_error(kCalledNonCallable, callback);
  }

  var i = 0;
    // 参数只有callback时,current作第一个参数
  find_initial: if (argumentsLength < 2) {
    for (; i < length; i++) {
      if (i in array) {
      
  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值