javascript - 通过逗号和 "and"连接数组

标签 javascript arrays string

我想转换数组['one', 'two', 'three', 'four']进入one, two, three and four

请注意,第一项有逗号,但有单词 and在倒数第二个和最后一个之间。

我想出的最佳解决方案:

a.reduce( (res, v, i) => i === a.length - 2 ? res + v + ' and ' : res + v + ( i == a.length -1? '' : ', '), '' )

它基于在末尾添加逗号 - 但倒数第二个逗号 ( a.length - 2 ) 除外,并且有一种方法可以避免最后一个逗号 ( a.length - 2 )。

肯定有更好、更简洁、更智能的方法来做到这一点吗?

这是一个很难在搜索引擎上搜索的主题,因为它包含“和”一词...

最佳答案

一个选项是弹出最后一项,然后用逗号加入所有其余项,并用and加上最后一项连接:

const input = ['one', 'two', 'three', 'four'];
const last = input.pop();
const result = input.join(', ') + ' and ' + last;
console.log(result);

如果无法改变输入数组,请使用 slice 代替,如果输入数组中可能只有一项,请先检查数组的长度:

function makeString(arr) {
  if (arr.length === 1) return arr[0];
  const firsts = arr.slice(0, arr.length - 1);
  const last = arr[arr.length - 1];
  return firsts.join(', ') + ' and ' + last;
}

console.log(makeString(['one', 'two', 'three', 'four']));
console.log(makeString(['one']));

关于javascript - 通过逗号和 "and"连接数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53879088/

相关文章:

java - Java 中的 str.contains

javascript - setTimeout 干扰加载事件处理程序的问题

javascript - 如何从异步调用返回响应?

javascript - 正则表达式问题 - 未知的空格

javascript - 将文本框值传递给唯一标签?

php - 如何获取没有模式且以 php 结尾的 URL 主机?

Python Numpy 数组运算符 x += y 与 x = x + y 不同吗?

php - 获取存储为数组的值

c# - 从字符串中读取坐标

c - 返回 C 中的字符串数组