我试图弄清楚如何返回一个句子,其中我有一个项目列表,并且必须用“,”分隔它们。但是,如果数组仅包含一个项目,您将只返回不带逗号的单词,如果有两个单词,则您将在第一个单词之后返回一个逗号,而不是最后一个单词。
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 + ".");
最佳答案
简单的方法是将每个元素附加到字符串中,后跟 ', '
,然后在返回字符串之前删除尾随的 ', '
。
/*
* 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 + ".");
关于javascript - 不使用 .join() 连接数组中的项目列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48272147/