简体   繁体   English

我尝试编写自己的Array.prototype.join()有什么问题?

[英]What's wrong with my attempt to write my own Array.prototype.join()?

I have been trying to implement a bunch of higher order functions myself. 我一直在尝试自己实现一堆高阶函数。 Just for the fun of it. 就是图个好玩儿。

Today though, I found myself stuck on the attempt to reproduce the Array.join method. 但是今天,我发现自己一直在尝试重现Array.join方法。

I have set myself a challenge not to use any loops such as for or while , use as little if statements as possible and reduce the number of variables used. 我面临的挑战是不使用诸如forwhile类的任何循环,使用尽可能少的if语句并减少使用的变量数量。

Below is my attempt: 以下是我的尝试:

 Array.prototype.implode = function(glue) { return (function loop(arr, str) { return (arr.length > 1 ? loop(arr.slice(0, 1), str + arr[0] + (glue || '')) : str); })(this, ''); }; const arr = ['a', 'b', 'c', 'd', 'e', 'f']; console.log(arr.implode('#')); // a# 

You should start handling the end case of a recursive function, than the other. 您应该开始处理递归函数的结束情况,而不是其他情况。 It's easier :) 更容易:)

However, you should slice from the second element to the end, not only the first element. 但是,您应该从第二个元素到最后一个切片,而不仅仅是第一个元素。

 Array.prototype.implode = function (glue) { return (function loop(array, glue) { return ( array.length === 1 ? array[0] : array[0] + glue + loop(array.slice(1), glue) ) })(this, glue || '') } const arr = ['a', 'b', 'c', 'd', 'e', 'f']; console.log(arr.implode('#')); // a#b#c#d#e#f 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM