最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - Convert a Javascript array into a readable string - Stack Overflow

programmeradmin5浏览0评论

If you have an array of strings in JavaScript / JQuery:

var myStrings = ["item1", "item2", "item3", "item4"];

...what is the most elegant way you have found to convert that list to a readable english phrase of the form:

"item1, item2, item3 and item4"

The function must also work with:

var myStrings = ["item1"]; // produces "item1"
var myStrings = ["item1", "item2"]; // produces "item1 and item2"

If you have an array of strings in JavaScript / JQuery:

var myStrings = ["item1", "item2", "item3", "item4"];

...what is the most elegant way you have found to convert that list to a readable english phrase of the form:

"item1, item2, item3 and item4"

The function must also work with:

var myStrings = ["item1"]; // produces "item1"
var myStrings = ["item1", "item2"]; // produces "item1 and item2"
Share Improve this question asked Jan 24, 2011 at 14:12 Mark RobinsonMark Robinson 13.3k13 gold badges65 silver badges83 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 14

Like this:

a.length == 1 ? a[0] : [ a.slice(0, a.length - 1).join(", "), a[a.length - 1] ].join(" and ")
发布评论

评论列表(0)

  1. 暂无评论