如何为返回值添加一个分隔符,并给分隔符一个默认值?

How do I add a delimiter to the returned value, and give delimiter a default value?

我遇到的问题是,我需要更改此代码以便为返回值添加定界符,并为定界符提供默认值。 我尝试了一些如果但是非常不必要并且让自己非常困惑。

var stringRepeater = function (string, times, delimiter) {
var repeatedString = string;

for (var i = 1; i < times; i++) {
 repeatedString += string;
  }
return repeatedString;
}

=================如果正确工作,这将是输出================

console.log(stringRepeater("hi", 3, ",") === "hi,hi,hi");
// -> true
console.log(stringRepeater("hi", 3) === "hi hi hi");
// -> true

您的代码非常接近。您可以在循环内添加定界符并包含一个默认参数(如果未指定以匹配您想要的结果):

var stringRepeater = function (string, times, delimiter=" ") {
  //                                                   ^^^^
  var repeatedString = string;

  for (var i = 1; i < times; i++) {
    repeatedString += delimiter + string;
    //                ^^^^^^^^^^^^
  }

  return repeatedString;
};

console.log(stringRepeater("hi", 3, ",") === "hi,hi,hi");
console.log(stringRepeater("hi", 3) === "hi hi hi");

小心 times < 1 时的极端情况——你仍然会重复一次。如果愿意,您可以抛出异常或 return 一个空字符串。

或者,您可以使用 Array constructor to build an array of a certain length, .fill the array with string s, then .join 使用参数定界符的数组(如果未指定定界符,则为 " ")。

const stringRepeater = (s, times, delim=" ") =>  
  Array(times).fill(s).join(delim)
;

另一个值得了解的类似功能是String#repeat, which almost does what you want, but not quite because it'd have a dangling delimiter, so you have to slice它关闭:

const stringRepeater = (s, times, delim=" ") =>  
  (s + delim).repeat(times).slice(0, -delim.length)
;