簡體   English   中英

如何構建消息字符串,在存在時使用數組值

[英]how to build a message string, using array values when present

我試圖向用戶顯示警告,我拆分了一個數組,並始終使用 0 和 1 位置值,有時該數組可能包含位置 2 中的值,並非總是如此。

我想構建消息字符串以顯示 arr[2] 的值(如果存在),或者僅顯示 arr[0],如果不存在 arr[2] 則顯示 arr[1]。

我試圖這樣做:

strWarningMsg =

    arr[2].length > 0 ? arr[1] + arr[2] + ' meeting, ' + '\nscheduled for: ' + arr[0].replace(/ +/g, " ")
    + '; data has been already uploaded.\n' + '\n Changes to the existing data could potentially invalidate any existing registration(s). Make sure to use the Cross-Reference file template before you attempt a new upload for this meeting.'
    + '\n\nPress OK to overwrite the existing Cross Reference List, or\nPress Cancel to abort the operation.'
   : arr[1] + ' meeting, ' + '\nscheduled for: ' + arr[0].replace(/ +/g, " ")
    + '; data has been already uploaded.\n' + '\n Changes to the existing data could potentially invalidate any existing registration(s). Make sure to use the Cross-Reference file template before you attempt a new upload for this meeting.'
    + '\n\nPress OK to overwrite the existing Cross Reference List, or\nPress Cancel to abort the operation.';

僅僅通過查看它並看到冗余,我就知道我做錯了,或者不是最佳實踐。 但不知何故它有效,但只有當 arr[2] 有一個值,因為我檢查 arr[2] 長度的部分,如果不存在,則代碼中斷。

是否有人可以向我展示如何正確使用三元運算符來實現此目標?

謝謝你,埃拉斯莫。

const prefix = (arr.length > 2 ? arr[1] + arr[2] : arr[1]);
const strWarningMsg = `${prefix} meeting,
scheduled for: ${arr[0].replace(/ +/g, " ")}; data has been already uploaded.

Changes to the existing data could potentially invalidate any existing registration(s). Make sure to use the Cross-Reference file template before you attempt a new upload for this meeting.

Press OK to overwrite the existing Cross Reference List, or\nPress Cancel to abort the operation.`;

拉出前綴並根據數組中的元素數量派生它。 此外,如果您將字符串更改為字符串文字,您可以在字符串中使用文字換行符,而不是\\n並使其更具可讀性。

暫無
暫無

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

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