在字符串上实现array.protype.reduce()
implement array.prototype.reduce() on string
我对如何在字符串上进行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
是一个字符串(数组中的第一个元素),当first
和last
都是字符串时,您的函数是有意义的,所以当回调只调用一次(数组最多有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
,并遵循其调用的方式
foo(0, "i am a boy")
给出NaN
foo(NaN, " she loves cats")
给出NaN
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);
}
在这种情况下,你会得到
foo(0, "i am a boy")
给出10
foo(10, " she loves cats")
给出15
foo(15, " a goat ate my flower garden ")
给出29
给出了CCD_ 27。
相关文章:
- 对一个对象使用reduce可以返回一个没有't在数组中包含目标字母
- 节点中的Map Reduce
- 对于这种情况,函数Reduce CouchDB
- 我们可以用参数对象集合而不是原始数据来调用JavaScript collection.reduce()方法吗
- 解构javascript中的reduce函数
- 关于reduce在javascript中创建过滤器的说明
- 为什么 Array.prototype.reduce() 不接受 Map 对象作为初始值
- 为什么Object.protype.toString.call(foo)可以检测到foo's类型
- 在javascript中使用reduce对数组中的变量求和
- Map/Reduce给我NaN或错误的结果(由于null)
- Undercore reduce,关于备忘录
- Object.protype.toString.call(),为什么在大多数示例中它's已使用的call()改为
- Array.prototype.reduce的实际用途是什么
- MongoDB map/reduce,forEach不是一个函数
- 使用map/reduce计算总数
- Javascript作用域规则和mongo-map/reduce函数
- 在MooTools中,什么'implement和.protype之间的区别是什么
- Javascript _.reduce() exercise
- 用函数重写reduce方法
- 在字符串上实现array.protype.reduce()