我想转换数组['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/