如果我在Javascript中有一个看起来像
的数组searchComponents = ['element1', 'element2', 'element3'];
将其变成如下句子的必要逻辑是什么:
" element1,element2和element3"
同样,如果只有两个元素,它应该是:
" element1和element2"
依此类推。我被卡住了。
答案 0 :(得分:19)
一个简单的解决方案:
function arrayToSentence (arr) {
var last = arr.pop();
return arr.join(', ') + ' and ' + last;
}
console.log(arrayToSentence(['one','two','three']));
一个稍微复杂/荒谬的解决方案(因为谁不喜欢傻,偶尔......):
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']));
参考文献:
答案 1 :(得分:16)
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
答案 2 :(得分:2)
答案 3 :(得分:2)
更多没有突变的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']);
答案 4 :(得分:2)
这是一个班轮:
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([]));
答案 5 :(得分:0)
这是怎么回事......
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.
在语法上正确吗?
答案 6 :(得分:0)
这是利用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
答案 7 :(得分:0)
最新答案,但这是我的尝试。相对简单,不可变的参数,适用于0-N个项目。
const toListSentence = (arr) => arr.length < 3 ?
arr.join(' and ') :
`${arr.slice(0, -1).join(', ')}, and ${arr[arr.length - 1]}`;
console.log(toListSentence([]));
console.log(toListSentence(['apple']));
console.log(toListSentence(['apple', 'banana']));
console.log(toListSentence(['apple', 'banana', 'peach']));