与节点一起下循环

在节点js我有一个函数,迭代通过数组来填充另一个元素。 有些时候,某些不确定的东西,怎么可能呢? 例如,我得到“不能读取未定义的属性formatPrice”。 节点上的for循环出了什么问题?

for (var i = 0; i < 10; i++) { //console.log(JSON.stringify(item.SmallImage)); message.attachment.payload.elements[i] = { "title":items[i].ItemAttributes.Title, "image_url": items[i].LargeImage.URL, "subtitle":items[i].ItemAttributes.ListPrice.FormattedPrice, "default_action": { "type": "web_url", "url": "https://www.google.it", "messenger_extensions": true, "webview_height_ratio": "tall", "fallback_url": "https://www.google.it" }, "buttons":[ { "type":"web_url", "url":"https://www.google.it", "title":"View Website" },{ "type":"postback", "title":"Start Chatting", "payload":"DEVELOPER_DEFINED_PAYLOAD" } ] } //sendMessage( senderId, {text: item.ItemAttributes.Title+" PREZZO**:"+item.ItemAttributes.ListPrice.FormattedPrice}); } 

cannot read property formattedPrice of undefined表示您尝试访问的对象formattedPrice, items[i].ItemAttributes.ListPrice ,为null / undefined。

为了防止发生错误,您应该在将值分配给message.attachment.payload.elements[i]之前包含一些validation。

 for (var i = 0; i < 10; i++) { var subtitle = "N/A"; if (items[i].ItemAttributes.ListPrice == null) { subtitle = items[i].ItemAttributes.ListPrice.FormattedPrice; } message.attachment.payload.elements[i] = { ... "subtitle": subtitle, // will now show as "N/A" instead of causing program to crash ... }; } 

另一件要考虑的事情是,在for循环中,除非条件为i < 10 ,否则将其replace为i < items.length ,除非您确定项目列表将始终包含10个或更多个元素。