Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
366 views
in Technique[技术] by (71.8m points)

js基础问题reduce的使用

[].reduce.call('cbaacfdeaebb',function(p,n){ return p[n] = (p[n] || 0) + 1,p; },{}),

看到过这样的代码,不太明白工作原理。reduce通过call就能应用到string上?有什么限制没有?工作原理是?能把string换成其他类型吗?比如map。
js新手,希望大神能详细讲解一下。


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

JavaScript数组方法是特意定义为通用的,因此他们不仅应用在真正的数组而且在类数组对象上也能正确工作,但是类数组对象没有继承自Array.prototype,所以可以通过Function.call间接地调用。

String可以作为类数组对象使用,因为有数值length属性和对应非负整数属性。


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...