javascript - 不使用 .join() 连接数组中的项目列表

标签 javascript

我试图弄清楚如何返回一个句子,其中我有一个项目列表,并且必须用“,”分隔它们。但是,如果数组仅包含一个项目,您将只返回不带逗号的单词,如果有两个单词,则您将在第一个单词之后返回一个逗号,而不是最后一个单词。

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/

相关文章:

javascript - 使用 Math.max 和 Math.min 从数组中删除最大和最小数字

javascript - Google Analytics(分析)目标不起作用

javascript - 将对象引用传递给 javascript 异步函数,但得到了意外的值

javascript - 按顺序将段落附加到图像属性? (第 1 到第 1,第 2 到第 2 ...第 n 到第 n 个)JQUERY

javascript - 为什么 IE 在 Debug模式下只是跳过错误并继续执行,但在没有调试的情况下它会停止执行 js?

javascript - React — componentDidUpdate 作为 promise /回调。是否可以?

javascript - 如何在修改后恢复图像的宽度和高度

javascript - 通过引用传递对象时 $OnChange 不会触发

javascript - Safari 和 Safari 移动设备上的 Iframe localStorage

javascript - 从网络应用程序调用 FB.login() 时,官方 Facebook iOS 应用程序总是崩溃