[英]Conditional array.join in Javascript
I have an array of strings and I would like to display them as a comma separated string but add "and" for the last element. 我有一个字符串数组,我想将它们显示为逗号分隔的字符串,但为最后一个元素添加“和”。 For example I have
比如我有
var fruits = ["Banana", "Orange", "Apple", "Mango"];
var energy = fruits.join(' ,');
outputs 输出
'Banana, Orange, Apple, Mango'
Is there any way the I add "and" for the last word so it outputs 是否有任何方法我为最后一个单词添加“和”以便输出
'Banana, Orange, Apple and Mango'
You can join the first 3 elements of the array using slice and join then append the last element concatenated with 'and'. 您可以使用切片和连接加入数组的前3个元素,然后追加与'和'连接的最后一个元素。
var fruits = ["Banana", "Orange", "Apple", "Mango"];
var energy = fruits.slice(0, fruits.length - 1).join(', ');
energy += ' and ' + fruits[fruits.length - 1];
You may instead use Array.reduce
function and implement your own logic, for example: 您可以改为使用
Array.reduce
函数并实现自己的逻辑,例如:
var fruits = ["Banana", "Orange", "Apple", "Mango"];
var energy = fruits.reduce(function (p, d, i) {
return p + (i === fruits.length - 1 ? ' and ' : ', ') + d;
});
You can try this, 你可以试试这个,
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);
Function toSentence of underscore.string has the exact functionality you want. 函数to undersity of underscore.string具有您想要的确切功能。 If you don't want to get whole library, you could just borrow
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;
};
You can't pass a function to .join
, unfortunately, so you do need to iterate through the loop and join it yourself: 遗憾的是,您无法将函数传递给
.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)
You could make a function for this, though: 但是你可以为此做一个函数:
// 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']))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.