数组的第一个对象没有被传递给reduce()中的initialValue参数

时间:2016-10-07 01:46:15

标签: javascript arrays

这是我的代码:

var deliveries = [
  {
    "id": 1,
    "destination": 'Oakland',    
    "orderPrice": 75,
    "rushDelivery": true,
    "rushDeliveryFee": 12.75,
    "orderDate": "4 April 2016" 
  },
  {
    "id": 2,
    "destination": 'San Jose',    
    "orderPrice": 62.75,
    "orderDate": "5 April 2016" 
  },
  {
    "id": 3,
    "destination": 'San Francisco',    
    "orderPrice": 15.00,
    "rushDelivery": true,
    "rushDeliveryFee": 50.75,
    "orderDate": "10 April 2016" 
  },
  {
    "id": 4,
    "destination": 'San Francisco',    
    "orderPrice": 25,
    "orderDate": "4/11/2016"
  },
  {
    "id": 5,
    "destination": 'San Francisco',    
    "orderPrice": 90,
    "rushDelivery": true,
    "rushDeliveryFee": 30,
    "orderDate": "April 12, 2015"
  },
  {
    "id": 6,
    "destination": 'Berkeley',    
    "orderPrice": 45,
    "orderDate": "4/01/2015"
  },
  {
    "id": 7,
    "destination": 'Berkeley',    
    "orderPrice": 62.16,
    "orderDate": "12 April 2016"
  }
];


var orderPrices = deliveries.reduce(function(prev, current) {
    return prev.orderPrice + current.orderPrice
})

console.log(orderPrices);

当我在console.log的第一次迭代中prev.orderPrice reduce()打印undefined时,但根据我的理解,如果你没有给出第二个参数({{1} }}}到initialValue,它只是默认为应用函数的数组的第一个元素。我希望打印数组的第一个对象。实际上,如果我们尝试使用另一个更简单的数组reduce()var arr = [1,2,3,4,5]在第一次迭代中打印1。

为什么会这样?

1 个答案:

答案 0 :(得分:0)

数组中的元素从左到右逐个减少1。因此,从第二次迭代开始, public void LoadTaskList() { List<string> taskList = dbHelper.getTaskList(); if (mAdapter == null) { mAdapter = new CustomAdapter(this, taskList,dbHelper); lstTask.Adapter = mAdapter; } } 参数已经是当前的总值:

prev