JavaScript逗号列表,但最后有一个和 [英] Javascript comma list but has an and at the last one
本文介绍了JavaScript逗号列表,但最后有一个和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试创建一个函数,该函数将包含单词列表-并将其隐藏为这样的句子.
jsfiddle
http://jsfiddle.net/0ht35rpb/107/
//数组列表
内容":{"0":[情绪困扰",行为困难",活动过度和注意力集中困难",与其他年轻人相处的困难"],"5":[有益和有益的行为"]}
//句子
情绪困扰,行为困难,活动过度和专注困难的得分很高,与其他年轻人相处的困难也很高.< p>友善和乐于助人的分数很低"//当前功能
grammarCheck:函数(值){//x,y,z和d//zvar count = vals.length;var text = vals.join(',')//返回[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?":和");返回文字}
解决方案
这应该有效.
函数createSentence(array){如果(array.length == 1){返回数组[0];}否则,如果(array.length == 0){返回 "";}var leftSide = array.slice(0,array.length-1).join(,");返回leftSide +和" + array [array.length-1];}console.log(createSentence(["dogs","cats","fish"])));console.log(createSentence(["dogs","cats"])));console.log(createSentence(["dogs"])));console.log(createSentence([]));
I am trying to create a function that will take a list of words -- and covert it into a sentence like this.
jsfiddle
http://jsfiddle.net/0ht35rpb/107/
// array list
"contents": {
"0": ["emotional distress", "behavioural difficulties", "hyperactivity and concentration difficulties", "difficulties in getting along with other young people"],
"5": ["kind and helpful behaviour"]
}
//sentence
"<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>"
//current function
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
}
解决方案
This should work.
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([]));
这篇关于JavaScript逗号列表,但最后有一个和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文