For Loop:TypeError:无法读取属性' 0'未定义的

时间:2016-11-03 12:48:28

标签: javascript arrays json object for-loop

我正在尝试循环返回从API请求返回的一些数据,其结构如下:

[ { kind: 'qpxexpress#tripOption',
    saleTotal: 'USD107.70',
    id: 'fANabOjuLoDMb9zppwbeXL002',
    slice: [ [Object] ],
    pricing: [ [Object] ] },
  { kind: 'qpxexpress#tripOption',
    saleTotal: 'USD107.70',
    id: 'fANabOjuLoDMb9zppwbeXL003',
    slice: [ [Object] ],
    pricing: [ [Object] ] },
  { kind: 'qpxexpress#tripOption',
    saleTotal: 'USD107.70',
    id: 'fANabOjuLoDMb9zppwbeXL001',
    slice: [ [Object] ],
    pricing: [ [Object] ] } ]

然而,我的for循环给了我一个类型错误,我很难调试。我错过了什么?

  request(options)
  .then(function (response) {
    //.log(response.trips.tripOption)
    let selects = 0
    for(let i = 0; i < response.trips.tripOption.length; i++) {
      if (response.trips.tripOption[i].selected) {
        selects++
      }
    }
    return selects
    console.log('hello' + ' ' + selects)

  })
  .catch(function (err) {
    console.log(err)
  })

1 个答案:

答案 0 :(得分:2)

你的代码段中DROP TABLE IF EXISTS my_table; CREATE TABLE my_table (priority VARCHAR(12) NOT NULL PRIMARY KEY ,total INT NOT NULL ); INSERT INTO my_table VALUES ('west',1), ('north',0), ('south',2), ('east',0); SELECT * , CASE FIND_IN_SET(total,(SELECT GROUP_CONCAT(DISTINCT total ORDER BY total DESC) x FROM my_table)) WHEN 1 THEN 'active' WHEN 2 THEN 'previous' END status FROM my_table; +----------+-------+----------+ | priority | total | status | +----------+-------+----------+ | west | 1 | previous | | north | 0 | NULL | | south | 2 | active | | east | 0 | NULL | +----------+-------+----------+ UPDATE my_table SET total = 4 WHERE priority = 'west'; SELECT * , CASE FIND_IN_SET(total,(SELECT GROUP_CONCAT(DISTINCT total ORDER BY total DESC) x FROM my_table)) WHEN 1 THEN 'active' WHEN 2 THEN 'previous' END status FROM my_table; +----------+-------+----------+ | priority | total | status | +----------+-------+----------+ | west | 4 | active | | north | 0 | NULL | | south | 2 | previous | | east | 0 | NULL | +----------+-------+----------+ 收到了一个拼写错误,写了Line 6而不是tripOptions

另外,tripOption之前应该console.log()