我有一个字符串数组,我想将它们显示为逗号分隔的字符串,但为最后一个元素添加“和”。例如,我有
var fruits = ["Banana", "Orange", "Apple", "Mango"];
var energy = fruits.join(' ,');
输出
'Banana, Orange, Apple, Mango'
有没有办法为最后一个单词添加“和”,以便输出
'Banana, Orange, Apple and Mango'
答案 0 :(得分:5)
您可以使用切片和连接加入数组的前3个元素,然后追加与'和'连接的最后一个元素。
var fruits = ["Banana", "Orange", "Apple", "Mango"];
var energy = fruits.slice(0, fruits.length - 1).join(', ');
energy += ' and ' + fruits[fruits.length - 1];
答案 1 :(得分:2)
您可以改为使用Array.reduce
函数并实现自己的逻辑,例如:
var fruits = ["Banana", "Orange", "Apple", "Mango"];
var energy = fruits.reduce(function (p, d, i) {
return p + (i === fruits.length - 1 ? ' and ' : ', ') + d;
});
答案 2 :(得分:1)
你可以试试这个,
var delimiter = ', ';
var fruits = ["Banana", "Orange", "Apple", "Mango"];
var energy = fruits.join(delimiter);
var index = energy.lastIndexOf(delimiter);
energy = energy.substring(0, index) + ' and ' + energy.substring(index + delimiter.length);
console.log(energy);

答案 3 :(得分:1)
underscore.string的函数toSentence具有您想要的确切功能。如果您不想获得整个图书馆,可以借用toSentence
:
function toSentence(array, separator, lastSeparator, serial) {
separator = separator || ', ';
lastSeparator = lastSeparator || ' and ';
var a = array.slice(),
lastMember = a.pop();
if (array.length > 2 && serial) lastSeparator = separator + lastSeparator;
return a.length ? a.join(separator) + lastSeparator + lastMember : lastMember;
};
答案 4 :(得分:1)
不幸的是,您无法将函数传递给.join
,因此您需要遍历循环并自行加入:
const array = ['banana', 'apple', 'taco']
let result = array[0]
for (let i = 1; i < array.length; i++) {
if (i < array.length - 1) {
result += ', ' + array[i]
} else {
result += ' and ' + array[i]
}
}
console.log(result)
&#13;
你可以为此制作一个函数,但是:
// General purpose custom/dynamic join function creator.
function dynamicJoin(fn) {
return function(array) {
let result = array[0]
for (let i = 1; i < array.length; i++) {
const joiner = fn(array[i - 1], array[i], i, array)
result += joiner + array[i]
}
return result
}
}
const joinCommaOrAnd = dynamicJoin(function(a, b, i, arr) {
return (i === arr.length - 1) ? ' and ' : ', '
})
console.log(joinCommaOrAnd(['bread', 'fish', 'butter']))
&#13;