用逗号和“和"将数组连接起来 [英] Join an array by commas and "and"

查看:55
本文介绍了用逗号和“和"将数组连接起来的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将数组 ['one','two','thre','four'] 转换为 1、2、3和4

请注意,第一项带有逗号,但是倒数第二个和最后一个之间有单词.

我想出的最佳解决方案:

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

它基于在处添加逗号的方式-除了倒数第二个( a.length-2 )以外,还有一种避免最后一个逗号( a.length-2 ).

肯定有一种更好,更整洁,更聪明的方式来做到这一点吗?

这是一个很难在搜索引擎上进行搜索的主题,因为它包含单词"and" ...

解决方案

一个选项是 pop 最后一个项目,然后 join 其余的所有内容都用逗号分隔,然后与以及最后一项连接:

  const input = ['一个','两个','三个','四个'];const last = input.pop();const result = input.join(',')+'和'+ last;console.log(result);  

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

  function makeString(arr){如果(arr.length === 1)返回arr [0];const firsts = arr.slice(0,arr.length-1);const last = arr [arr.length-1];返回firsts.join(',')+'和'+ last;}console.log(makeString(['一个','两个','三个','四个'])));console.log(makeString(['one']));  

I want to convert the array ['one', 'two', 'three', 'four'] into one, two, three and four

Note that the first items have a comma, and but there is the word and between the second-last one and the last one.

The best solution I've come up with:

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

It's based on adding the commas at the end -- with the exception of the second-last one (a.length - 2) and with a way to avoid the last comma (a.length - 2).

SURELY there must be a better, neater, more intelligent way to do this?

It's a difficult topic to search on search engines because it contains the word "and"...

解决方案

One option would be to pop the last item, then join all the rest by commas, and concatenate with and plus the last item:

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

If you can't mutate the input array, use slice instead, and if there might only be one item in the input array, check the length of the array first:

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']));

这篇关于用逗号和“和"将数组连接起来的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆