如何构建消息字符串,在存在时使用数组值

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

我试图向用户显示警告,我拆分了一个数组,并始终使用 0 和 1 位置值,有时数组可能包含位置 2 的值,但并非始终如此。

我想构建消息字符串以显示 arr[2] 的值(如果存在),或者仅显示 arr[0] 和 arr[1](如果不存在 arr[2])。

我试过这样做:

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] 长度的部分,如果不存在,那么代码就会中断。

有人可以告诉我如何正确使用三元运算符来实现这个目标吗?

谢谢你, Erasmo.

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 并使其更具可读性。