繁体   English   中英

是否可以在 JavaScript 中使用 reduce 和字符串?

[英]Is it possible to use reduce with strings in JavaScript?

我想知道是否也可以在带有字符串的数组上使用reduce方法?

例如:如果我有一个这样的数组: [ 'm', 'o', 'o', 'n' ]那么我可以将它简化为这样的对象: { m: 1, o: 2, n: 1 } ,计算字符串中所有字符的出现次数。
但是,如果我有一个字符串"moon" ,我将无法使用reduce方法。

我知道我可以为reduce编写自定义实现,但是有更简单的吗?

的,因为Array.prototype.reduce是一个泛型方法,它不需要this必须是一个数组。 这意味着reduce不仅设计用于处理数组,还用于处理其他类似数组的值,如字符串。

并且为了将reduce与字符串str一起使用,您可以使用Function.prototype.call在字符串上调用它。

 const str = "moon"; const strCharCount = Array.prototype.reduce.call( str, (r, s) => { r[s] = (r[s] ?? 0) + 1; return r; }, {} ); console.log(strCharCount);

如果所有这些都没有任何意义,您还可以将字符串转换为数组并像往常一样使用reduce

 const str = "moon"; const strCharCount = Array.from(str).reduce((r, s) => { r[s] = (r[s] ?? 0) + 1; return r; }, {}); console.log(strCharCount);

暂无
暂无

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

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