首页 > 解决方案 > 即使我声明 typeof !== undefined 仍然尝试读取未定义的纬度

问题描述

 UserScheme.pre('save', async function(next){
     const code = await geocoder.geocode(this.address)
     console.log(this.address)
     console.log(code)

所以我前段时间遇到了这个麻烦,所以我尝试这样做:

     if(typeof code !== "undefined"){
         this.lat = code[0].latitude
         this.lng = code[0].longitude
     }

但它仍然返回:

 TypeError: Cannot read property 'latitude' of undefined

标签: node.jsgeocoding

解决方案


好吧,您还可以检查代码是否是一个数组并且至少有一个元素,例如:

if (Array.isArray(code) && code[0]) { ... 做点什么... }


推荐阅读