2017-08-30 117 views
-5

我想創建一個函數,將採取單詞列表 - 並將其轉換爲像這樣的句子。Javascript逗號清單,但有一個,並在最後一個

的jsfiddle

http://jsfiddle.net/0ht35rpb/107/

//數組列表

"contents": { 
    "0": ["emotional distress", "behavioural difficulties", "hyperactivity and concentration difficulties", "difficulties in getting along with other young people"], 
    "5": ["kind and helpful behaviour"] 
} 

//句子

"<p>Score for emotional distress, behavioural difficulties, hyperactivity and concentration difficulties very high and difficulties in getting along with other young people very high</p> 
<p>Score for kind and helpful behaviour very low</p>" 

//當前功能

grammarCheck : function(vals) { 
    //x,y,z and d 
    //z 
    var count = vals.length; 

    var text = vals.join(', ') 

    //return [ this.props.data.contents[key].slice(0, -1).join(", "), this.props.data.contents[key].slice(-1)[0] ].join(this.props.data.contents[key].length < 2 ? "" : " and "); 

    return text 
} 
+1

什麼是錯誤? – SuperStormer

+0

那麼錯誤 - 或者只是做一個逗號列表 - 或者不放在文本的正確部分。 –

+0

// x,y,z,d ---代替// x,y,z和d –

回答

1

這應該工作。

function createSentence(array) { 
 
    if (array.length == 1) { 
 
    return array[0]; 
 
    } else if (array.length == 0) { 
 
    return ""; 
 
    } 
 
    var leftSide = array.slice(0, array.length - 1).join(", "); 
 
    return leftSide + " and " + array[array.length - 1]; 
 
} 
 

 
console.log(createSentence(["dogs", "cats", "fish"])); 
 
console.log(createSentence(["dogs", "cats"])); 
 
console.log(createSentence(["dogs"])); 
 
console.log(createSentence([]));

+0

_將始終產生尾隨,並且 - 如果它的只有1個詞 - 如最後一個列表中所示 –

+0

另外,它不會根據對象鍵 – Dallen

+0

對輸出進行排名我更關心它總是噴出「和「 - 即使它只有一個單詞 –

0

一種方法是刺痛

function grammarCheck(vals) { 
 
     //x,y,z and d 
 
     //z 
 
     var count = vals.length; 
 

 
     var last = vals.pop() 
 
     
 
     var text = vals.join(', ') + (vals.length > 1 ? ' and ' : '') + last 
 

 
     return text 
 
    } 
 
    
 
    
 
    var arr = [ 
 
      ["emotional distress"], 
 
      ["abc", "123", "blah", "blah", "blah"] 
 
    ] 
 
    
 
    arr.forEach(a => console.log('grammar check', grammarCheck(a)))

+0

- 如果使用正則表達式來查找和替換最後一個逗號,如果有和? –

0

功能您在流行過的最後一個項目,然後再加入並把最後一個項目已經評論出來似乎是正確的,除了它使用的一些財產而不是傳遞給它的參數。

調整,你會得到:

const grammarCheck = function(vals) { 
    return [ vals.slice(0, -1).join(", "), vals.slice(-1)[0] ] 
     .join(vals.length < 2 ? "" : " and "); 
} 
grammarCheck(['foo']); //=> 'foo' 
grammarCheck(['foo', 'bar']); //=> 'foo and bar' 
grammarCheck(['foo', 'bar', 'baz']); //=> 'foo, bar and baz' 
grammarCheck(['foo', 'bar', 'baz', 'qux']); //=> 'foo, bar, baz and qux' 

很顯然,如果你想Oxford comma你可以改變這一點。

+0

- 如果使用正則表達式來查找和替換最後一個逗號,如果有和? –

+0

@TheOldCounty:這可以做很多方法。但是這個代碼只是對問題中版本的調整。我不知道是否有任何問題。但是,根據實施方式的不同,在語法檢查([豌豆和胡蘿蔔,'豬肉和豆類','比薩和啤酒'))''等情況下,正則表達式解決方案可能會成爲受害者。這個解決方案不應該有這樣的問題。 –

相關問題