开发者问题收集

TypeError:推送代码后无法读取 null 的属性‘0’

2018-04-11
5934

控制台上显示的错误是:

TypeError: Cannot read property '0' of null
    at app.post (/root/src/master.js:24:29)

master.js 24:29 是这个

let outputs = req.body.outputs
  let outs = []
  for (let out of outputs) {
   outs.push({
     address: out.addresses[0],
      value: out.value
    })}
  }

第 24 行是地址: out.addresses[0],

来自此 json 的请求

"outputs": [
{
"value": 10000,
"script": "a91402f42dce015def2fab0b1d6f7f6c742bae66e75e87",
"addresses": [
"31xdnmzVzmAQ5CaWxtiDr3jwCFfeUpHEb1"
],
"script_type": "pay-to-script-hash"
},
{
"value": 1020,
"script": "0014396ef6487043092385338ccfe9d327fb031975d6",
"addresses": null,
"script_type": "pay-to-witness-pubkey-hash"
}
]

有人可以帮我解决这个问题吗?非常感谢!

3个回答

地址为空。您可以添加空值检查

let outputs = req.body.outputs
let outs = []
for (let out of outputs) {
    outs.push({
      address: out.addresses ? out.addresses[0] : '',
      value: out.value
    })}
}
rozalex
2018-04-11

由于您的 addresses 可以为空(根据您共享的示例输出),

for (let out of outputs) {
   outs.push({
     address: out.addresses ? out.addresses[0] : [], //notice the change here
      value: out.value
    })}
}

如果 out.addressesnull ,则设置一个 空数组

gurvinder372
2018-04-11

address 在对象中的某个地方为空,

因此,您可以添加一个条件,使用 三元 运算符检查 address 是否 存在

let outputs = req.body.outputs
  let outs = []
  for (let out of outputs) {
   outs.push({
     address: out.addresses ? out.addresses[0] : '',
      value: out.value
    })}
  }

address: out.addresses ? out.addresses[0] : '',

上面一行检查 out.addresses` 是否存在,如果是,它将返回该值,否则返回空字符串。

Sravan
2018-04-11