node.js - 即使我声明 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
解决方案
好吧,您还可以检查代码是否是一个数组并且至少有一个元素,例如:
if (Array.isArray(code) && code[0]) { ... 做点什么... }
推荐阅读
- python - 使用python解压缩gzip压缩字典对象
- jquery - 如何在 div 外部单击并隐藏,当我将它拖到外部时,它会一直隐藏(mouseup,mousedown ...)Jquery
- python - 是否有一个选项可以在 QFileDialog 的 SideBar 中重命名 QUrl/快捷方式?
- mysql - 如果一行状态值为 5,则 MySql 比较同一表中的行
- graphviz - Graphviz 作为独立的操作系统独立标准可执行文件
- c - 读取文件时输出错误
- python - 如果它出现在后续列中,则替换数据框列中的文本
- c# - 用于 C# 中大型数据集的 DataFrame
- ansible - 如何在 Ansible azure_rm conditional_groups 中使用多个语句
- c# - WCF : 添加服务失败。服务元数据可能无法访问。确保您的服务正在运行并公开元数据