簡體   English   中英

在JavaScript中查找對象列表

[英]Find objects list in Javascript

我有一個這樣的對象列表:

{code:"E21", msg:"Message of code E21", type:"blue"}
{code:"E22", msg:"Message of code E22", type:"red"}

我使用.find()返回特定代碼的消息,如下所示:

var eventCode = "E20";
var result =  iprsMsgList.find(result => result.code === eventCode);
var resultMsg = result.msg;

但是,如果找不到代碼,它將跳過消息並得到此錯誤

未捕獲的TypeError:無法讀取未定義的屬性'msg'

我需要做一些如何不跳過並給我一條消息,例如..找不到消息。

您可以使用條件(三元)運算符?:並檢查對象是否真實。

var resultMsg = result ? result.msg : 'not found';
var resultMsg = typeof result !== 'undefined' ? result.msg : 'message not found';

這應該夠了吧。 您需要檢查是否返回了一條消息,如果沒有返回,則返回您想要的字符串錯誤。 上面的三元是這樣做的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM