[英]Turn array into comma separated grammatically correct sentence
如果我在Javascript中有一个看起来像的数组
searchComponents = ['element1', 'element2', 'element3'];
将它变成如下句子的必要逻辑是什么:
“element1,element2和element3”
同样,如果只有两个元素,它应该如下:
“element1和element2”
等等等等。 我被卡住了。
简单的解决方案:
function arrayToSentence (arr) {
var last = arr.pop();
return arr.join(', ') + ' and ' + last;
}
console.log(arrayToSentence(['one','two','three']));
JS小提琴演示 。
还有一个稍微复杂/荒谬的解决方案(因为谁不喜欢傻,偶尔......):
function arrayToSentence (arr) {
var len = arr.length;
return arr.reduce(function(a,b,c){
return a + (c - 1 === length ? ', ' : ' and ') + b;
});
}
console.log(arrayToSentence(['one','two','three']));
JS小提琴演示 。
参考文献:
function toSentence(arr) {
return arr.slice(0, -2).join(', ') +
(arr.slice(0, -2).length ? ', ' : '') +
arr.slice(-2).join(' and ');
}
用法
toSentence([1])
1
toSentence([1, 2])
1和2
toSentence([1, 2, 3])
1,2和3
toSentence([1, 2, 3, 4, 5, 6])
1,2,3,4,5和6
更多没有突变的ES6 / 7版本:
function buildSentence (arr = []) {
if (arr.length === 0) {
return '';
}
if (arr.length === 1) {
return arr[0];
}
const newArr = [...arr];
const last = newArr.pop();
return newArr.join(', ') + ' and ' + last;
}
buildSentence([]);
buildSentence(['a']);
buildSentence(['a', 'b']);
buildSentence(['a', 'b', 'c']);
这是一个班轮:
const arrayToSentence = (a) => [a.slice(0, -1).join(', '), a.pop()].filter(w => w !== '').join(' and '); console.log(arrayToSentence(['foo', 'bar', 'baz'])); console.log(arrayToSentence(['foo', 'bar'])); console.log(arrayToSentence(['foo'])); console.log(arrayToSentence([]));
这个怎么样...
function parseArray(arr) {
var s=arr.toString();
var c=s.lastIndexOf(",");
if(c!=-1) s=(s.substr(0,c)+" and "+s.substr(c+1)).replace(/,/g,", ");
return s[0].toUpperCase()+s.substr(1)+".";
}
console.log(parseArray(["one", "two","three","four","five"]));
console.log(parseArray(["one", "two"]));
console.log(parseArray(["one"]));
输出是:
One, two, three, four and five.
One and two.
One.
在语法上正确吗?
这是一个使用lodash函数的打字版本:
import { concat, first, join, last, slice } from 'lodash'
function joinOxford (list: string[]): string {
switch (list.length) {
case 1: return first(list)
case 1: return `${first(list)} and ${last(list)}`
default: return join(concat(slice(list, 0, -1), [`and ${last(list)}`]), ', ')
}
}
用法:
joinOxford([foo])
// => foo
joinOxford([foo, bar])
// => foo and bar
joinOxford([foo, bar, baz])
// => foo, bar, and baz
joinOxford([foo, bar, baz, qux, quux, quuz])
// => foo, bar, baz, qux, quux, and quuz
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.