在所有数组元素之间添加“逗号”分隔符,并在最后一个数组元素之前添加“与” [英] Add 'commas' separator between all array elements and 'and' before the last array element

查看:961
本文介绍了在所有数组元素之间添加“逗号”分隔符,并在最后一个数组元素之前添加“与”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在一行中显示一个数组的数组项,并用逗号分隔,但最后一个数组项应以 and开头,并在最后一个元素的末尾添加句号。

I am trying to display array item of an array in a single line divided by 'commas' but the last array item should be preceded by 'and' and a full stop should be added at the end of the last element.

例如:

var cars = new Array("Saab", "Volvo", "BMW", "ZEST", "Audi");

应显示为萨博,沃尔沃,宝马,ZEST和奥迪。

var cars = new Array("Saab", "Audi");

如果只有2个项目,则应显示为萨博和奥迪。

If there are only 2 items then it should display as Saab and Audi.

var cars = new Array("Saab");

如果只有一项,则应显示为 Saab。

If there is only 1 item it should display as Saab.

数组长度是动态的,但应遵循上述格式,即所有数组项均应以逗号分隔,但最后第二个数组项与最后一个数组项之间应有 and 。

The array length is dynamic but it should follow the above format i.e. all array item should be separated by commas but there should be 'and' between 2nd last array item and last array item.

var cars = new Array("Saab", "Volvo", "BMW", "ZEST", "Audi");

for (i = 0; i < cars.length; i++) {

  var total = cars.length;
  var lastbut = total - 1;
  var disp;
  var addand = "";


  if (i != cars.length - 1) {
    disp = ", "
  } else {
    addand = "and "
    disp = "."
  }


  document.write(addand + cars[i] + disp);

}

https://jsfiddle.net/f01ph8pa/2/

我无法完成这个。

推荐答案

使用 slice 获取除数组中的最后一个字符串,并用逗号 join ;然后在数组中添加和和最后一个字符串。

Use slice to get all but the last string in the array and join them with a comma; then add " and " and the final string in the array.

function listStrings(arr) {
  if (arr.length <= 1) {
    return arr[0] + '.';
  }
  return arr.slice(0, arr.length - 1).join(", ") + ' and ' + arr[arr.length - 1] + '.';
}

listStrings(['A', 'B', 'C', 'D']); // returns "A, B, C and D."
listStrings(['A', 'B']);   // returns "A and B."
listStrings(['A']);   // returns "A."

https://jsfiddle.net/81ykw0uL/18

这篇关于在所有数组元素之间添加“逗号”分隔符,并在最后一个数组元素之前添加“与”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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