我正在试图找出如何返回一个句子,我有一个项目列表,我必须用“,”分隔它们。但是,如果数组只包含一个项目,则只返回没有逗号的单词,如果有两个单词,则在第一个单词之后返回一个逗号,而不是最后一个。
var conceptList = ['apple', 'orange', 'banana'];
var concepts = joinList(conceptList);
function joinList() {
for (var i = 0; i < conceptList.length; i++) {
if (conceptList.length) {
conceptList[i];
}
return conceptList;
}
}
console.log("Today I learned about " + concepts + ".");
答案 0 :(得分:1)
这样做的简单方法是将每个元素附加到字符串,然后是', '
,然后在返回字符串之前删除尾随', '
。
/*
* Write a loop that joins the contents of conceptList together
* into one String, concepts, with each list item separated from
* the previous by a comma.
*
* Note: you may not use the built-in Array join function.
*/
var conceptList = ['apple', 'orange', 'banana'];
// a custom function written by you (you must define it too!)
var concepts = joinList(conceptList);
function joinList() {
var str = '';
for (var i = 0; i < conceptList.length; i++) {
str += conceptList[i] + ', ';
}
return str.substr(0, str.length-2);
}
console.log("Today I learned about " + concepts + ".");
&#13;