实现正在传递3个参数的连接函数

时间:2016-08-21 02:36:01

标签: javascript join syntax concatenation

我希望完成此练习,请写一个名为join的函数,就像内置联接一样,但是使用reduce!



Let's write a function called join that works just like the built-in join, but using reduce! If you're unfamiliar with the built-in version of join, this is how it works:

["the", "quick", "brown", "fox"].join(" "); // => "the quick brown fox"
["one", "two", "three"].join(":"); // => "one:two:three"
Part One: First, write a function called joinWith that takes three arguments: the string to join onto, the string that will be joined, and a separator. That is, it should work like this:

function joinWith(onto, next, separator) {
  // YOUR CODE HERE
}
joinWith("the quick", "brown", " "); // => "the quick brown"
joinWith("one:two", "three", ":"); // => "one:two:three"
Part Two: Now, using joinWith and reduce, write join:

function join(array, separator) {
  // YOUR CODE HERE
}
join(["the", "quick", "brown", "fox"], " "); // => "the quick brown fox"
join(["one", "two", "three"], ":"); // => "one:two:three"




我写了以下代码:



var joinWith = function(start, toAdd, separt){

	 return reduce(arguments, function(start, toAdd){
	 	 return start + separt + toAdd; 
	 	  
	 }, " ");
}



 但是,我不确定为什么我会得到以下结果。



joinWith("one: two", "three", ":");
" :one: two:three::"




有人可以告诉我这里发生了什么,以及如何从字符串的前面和分隔符不应出现的区域中删除分隔符。

我非常感谢你的帮助。

1 个答案:

答案 0 :(得分:0)

目前正在发生什么:

您没有显示reduce()函数的实现,但假设它的工作方式与标准Array.prototype.reduce()相同,那么您的输出可以解释如下:

arguments是一个类似于数组的对象,包含以下值:

["one: two", "three", ":"]

当您在reduce()上致电arguments时,它会依次访问每个项目:

第一次迭代:start" ",从最后一个参数reduce()开始,toAdd"one: two"。从该迭代中返回字符串" :one: two"

第二次迭代:start" :one: two"(前一次迭代的返回值),toAdd"three",您返回" :one: two:three"。< / p>

第3次迭代:start" :one: two:three"(上一次迭代的返回值),toAdd":",您返回" :one: two:three::"

你应该做什么:

你知道这个函数有三个参数,所以只需使用:

function joinWith(start, toAdd, separt) {
  return start + separt + toAdd;
}

确实想要使用reduce()

当你的规范只加入两个字符串时,它确实是错误的工作工具,但如果你必须,你想在joinWith()的最后一个参数之外的所有字符串上使用它 - 注意如下所示,只要分隔符是最后一个参数,就可以传递任意数量的字符串来加入:

&#13;
&#13;
var joinWith = function(){
  if (arguments.length < 3) return arguments[0];
  var separt = arguments[arguments.length-1];
  return reduce(Array.prototype.slice.call(arguments,0,-1), function(start, toAdd){
    return start + separt + toAdd;
  }); // note: do not pass an initial value
}
    
console.log(joinWith("one: two", "three", ":"));
console.log(joinWith("one","two","three","four","five",":"));
console.log(joinWith("a","b","c","d","e",", "));
console.log(joinWith("x","y"));
    
// Dodgy simulation of your reduce() function for demo purposes only: 
function reduce(arr, cb) {
  return Array.prototype.reduce.call(arr, cb);
}
&#13;
&#13;
&#13;