亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

防止高階數組方法拋出錯誤

防止高階數組方法拋出錯誤

米琪卡哇伊 2024-01-18 16:47:37
有沒有辦法防止過濾時拋出錯誤?conversationMember.Name.toLowerCase()當沒有對話成員時,下面的函數有時會失敗。如果有幫助的話,這也是 Vue 應用程序中的計算屬性。如果您需要更多信息,請詢問!filteredConversations() {    var self = this;    var filteredConvos = self.conversations;    filteredConvos = filteredConvos.filter(conversation => {        return conversation.MembershipData.some(conversationMember => {            return conversationMember.Name.toLowerCase().includes(                self.conversationSearchTerm.toLowerCase()            );        });    });    return filteredConvos;},
查看完整描述

1 回答

?
當年話下

TA貢獻1890條經驗 獲得超9個贊

這似乎與數組沒有任何關系。

從你的代碼中我理解conversationMember.Name應該是 a?string(因為你正在調用.toLowerCase()它),這意味著incudes這里不是Array.prototype.includes, but?String.prototype.includes,特別是因為它self.conversationSearchTerm似乎也是一個字符串(你也在調用.toLowerCase()它)。

所以,問題是你正在使用includes一些應該是string但不是的東西。簡單的修復方法是當它為假時將其默認為空字符串:

return (conversationMember.Name || '').toLowerCase().includes(

? (self.conversationSearchTerm || '').toLowerCase()

);

附帶說明一下,您不需要var self = this;. this由于過濾器是一個箭頭函數,因此在過濾器內可用。所以你的函數(我猜它是 acomputed但它也可以是 a method)可能如下所示:


filteredConversations() {

? return this.conversations.filter(c =>?

? ? c.MembershipData.some(md =>?

? ? ? (md.Name || '').toLowerCase().includes(

? ? ? ? (this.conversationSearchTerm || '').toLowerCase()

? ? ? )

? ? )

? );

}

最后一點:如果您中的任何一個conversations沒有MembershipData持有數組,這仍然會失敗。為了解決這個問題,您可以將其默認為動態空數組:


?...

? ?(c.MembershipData || []).some(md =>?

?...

正如預期的那樣,任何沒有數組的對話都MembershipData將被函數過濾掉(不包含在結果中) - 因為.some(condition)在空數組上調用時將返回 false。


查看完整回答
反對 回復 2024-01-18
  • 1 回答
  • 0 關注
  • 124 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號