简体   繁体   English

将数组转换为逗号分隔语法正确的句子

[英]Turn array into comma separated grammatically correct sentence

If I have an array in Javascript that looks like 如果我在Javascript中有一个看起来像的数组

searchComponents = ['element1', 'element2', 'element3'];

What is the necessary logic to turn it into a sentence like: 将它变成如下句子的必要逻辑是什么:

"element1, element2, and element3" “element1,element2和element3”

Likewise, if there are only two elements it should read like: 同样,如果只有两个元素,它应该如下:

"element1 and element2" “element1和element2”

and so on and so forth. 等等等等。 I am stuck. 我被卡住了。

One easy solution: 简单的解决方案:

function arrayToSentence (arr) {
    var last = arr.pop();
    return arr.join(', ') + ' and ' + last;
}

console.log(arrayToSentence(['one','two','three']));

JS Fiddle demo . JS小提琴演示

And a slightly more complex/ridiculous solution (because who doesn't like silly, occasionally...): 还有一个稍微复杂/荒谬的解决方案(因为谁不喜欢傻,偶尔......):

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 Fiddle demo . JS小提琴演示

References: 参考文献:

function toSentence(arr) {
  return arr.slice(0, -2).join(', ') + 
    (arr.slice(0, -2).length ? ', ' : '') + 
    arr.slice(-2).join(' and ');
}

usage 用法

toSentence([1])

1 1

toSentence([1, 2])

1 and 2 1和2

toSentence([1, 2, 3])

1, 2 and 3 1,2和3

toSentence([1, 2, 3, 4, 5, 6])

1, 2, 3, 4, 5 and 6 1,2,3,4,5和6

Try my compound-subject library: 试试我的复合主题库:

https://github.com/adamshaylor/compound-subject https://github.com/adamshaylor/compound-subject

It includes controls over what character to delimit with (eg commas versus semicolons) as well as whether to delimit all the subjects (ie the “Oxford comma”). 它包括控制要划分的字符(例如逗号与分号)以及是否划分所有主题(即“牛津逗号”)。

More ES6/7 version without mutation: 更多没有突变的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']);

Here's a one liner: 这是一个班轮:

 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([])); 

How's this... 这个怎么样...

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

Output is: 输出是:

One, two, three, four and five.
One and two.
One.

Grammatically correct? 在语法上正确吗?

Here's a typed version that utilizes lodash functions: 这是一个使用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)}`]), ', ')
  }
}

Usage: 用法:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM