在字符串上实现array.protype.reduce()

implement array.prototype.reduce() on string

本文关键字:reduce protype array 字符串 实现      更新时间:2023-09-26

我对如何在字符串上进行reduce操作有些困惑。首先创建一个新的Str实例,并将所需的字符串作为参数发送。

然后使用split方法将其拆分为字符串数组。reduceIt方法获取数组并执行reduce操作,该操作返回具有高度长度的数组元素。

它适用于双元素数组。但如果有两个以上的元素,则返回NAN。

为什么对于包含两个以上元素的数组返回NAN??

function Str(text){
   this.text=text.split(''n');
}
Str.prototype.reduceIt = function() {
  return this.text.reduce(function(first,last,index,arr) {
          return Math.max(first.length,last.length);
  });
};
var t=new Str('i am a boy'n she loves cats'n a goat ate my flower garden ');
console.log(t.reduceIt());

第一次调用回调的first是一个字符串(数组中的第一个元素),当firstlast都是字符串时,您的函数是有意义的,所以当回调只调用一次(数组最多有2个元素)时,它就起作用了。

第二次调用它时,它是上一次调用的结果,即number。当你在某个号码上拨打first.length时,你会得到undefined,当你在该号码上拨打Math.max时,你就会得到NaN

如果你想找到数组中最长字符串的长度,你可以使用:

Math.max.apply(Math, this.text.map(function (str) { return str.length; }));

已经有了一些不错的答案。:-)

解决问题的简单方法是提供初始值0,然后将返回的值与新字符串的长度进行比较,因此:

Str.prototype.reduceIt = function() {
  return this.text.reduce(function(first,last,index,arr) {
          // Compare current value (first) with length of string
          return Math.max(first,last.length);
  }, 0); // supply 0 as the initial value
};

first重命名为maxSoFar,将last命名为currentString可能会更清楚。

为什么对于包含两个以上元素的数组返回NAN??

因为number.length是未定义的,所以让我们将函数命名为foo,并遵循其调用的方式

  1. foo(0, "i am a boy")给出NaN
  2. foo(NaN, " she loves cats")给出NaN
  3. foo(NaN, " a goat ate my flower garden ")给出NaN

给出了CCD_ 17的最终结果。

发生这种情况是因为number.length是未定义的,而Math.max(undefined, x)NaN

看起来你想写一个只占用第二个arg 的长度的函数

function foo(a, b) {
    return Math.max(a, b.length);
}

在这种情况下,你会得到

  1. foo(0, "i am a boy")给出10
  2. foo(10, " she loves cats")给出15
  3. foo(15, " a goat ate my flower garden ")给出29

给出了CCD_ 27。