Javascript 计算字符串中每个单词的出现次数,并将其放入对象中
我需要得到字符串中每个单词的总数 我想用reducer实现它,因为我是reduce方法的初学者,无法解决它Javascript 计算字符串中每个单词的出现次数,并将其放入对象中,javascript,arrays,object,Javascript,Arrays,Object,我需要得到字符串中每个单词的总数 我想用reducer实现它,因为我是reduce方法的初学者,无法解决它 getWordOccurence = (str1) => { splitStr = str1.split(' '); let count=0; const wordCount = splitStr.reduce((acc, curr) => ({...acc,[curr]:count}),{}) console.log(wordCount) }; getWor
getWordOccurence = (str1) => {
splitStr = str1.split(' ');
let count=0;
const wordCount = splitStr.reduce((acc, curr) => ({...acc,[curr]:count}),{})
console.log(wordCount)
};
getWordOccurence('apple orange apple banana grapes ?');
预期:{“苹果”:2,“橙色”:1,“香蕉”:1,“葡萄”:1}您可以尝试使用逗号运算符。我认为最好使用逗号运算符返回累加器,而不是使用扩展运算符
const getwordoccurrence=(str1)=>{
splitStr=str1.split(“”);
const wordCount=splitStr.reduce((ac,x)=>(ac[x]=ac[x]+1 | | 1,ac),{})
console.log(字数)
};
GetWordOccurrence(“苹果橙苹果香蕉葡萄”)代码>您可以尝试使用逗号运算符。我认为最好使用逗号运算符返回累加器,而不是使用扩展运算符
const getwordoccurrence=(str1)=>{
splitStr=str1.split(“”);
const wordCount=splitStr.reduce((ac,x)=>(ac[x]=ac[x]+1 | | 1,ac),{})
console.log(字数)
};
GetWordOccurrence(“苹果橙苹果香蕉葡萄”)
您可以选择字符串
并使用以获取结果对象
如果需要排除非单词,可以执行/[a-z]/i
检查c.match(/[a-z]/i)
代码:
const str='苹果橙苹果香蕉葡萄?';
const getwordoccurrence=s=>s.split(“”).reduce((a,c)=>{
如果(c.match(/[a-z]/i)){//仅单词。。。
a[c]=(a[c]| 0)+1;
}
返回a;
}, {});
const result=getWordOccurrence(str);
控制台日志(结果)
您可以选择字符串
并使用以获取结果对象
如果需要排除非单词,可以执行/[a-z]/i
检查c.match(/[a-z]/i)
代码:
const str='苹果橙苹果香蕉葡萄?';
const getwordoccurrence=s=>s.split(“”).reduce((a,c)=>{
如果(c.match(/[a-z]/i)){//仅单词。。。
a[c]=(a[c]| 0)+1;
}
返回a;
}, {});
const result=getWordOccurrence(str);
控制台日志(结果)代码>我想发布一个纯reducer版本
const getwordoccurrence=(str1)=>{
const splitStr=str1.split(“”);
const wordCount=splitStr.reduce((acc,x)=>({…acc,[x]:acc[x]+1}),{})
console.log(字数)
};
GetWordOccurrence(“苹果橙苹果香蕉葡萄”)代码>我想发布一个纯reducer版本
const getwordoccurrence=(str1)=>{
const splitStr=str1.split(“”);
const wordCount=splitStr.reduce((acc,x)=>({…acc,[x]:acc[x]+1}),{})
console.log(字数)
};
GetWordOccurrence(“苹果橙苹果香蕉葡萄”)
可能重复我真的不建议使用reduce。为此,您正在对每个对象执行reduce
,但使用reduce
@appleapplereduce
生成一个新对象,因此函数保持纯净。调用修改传递参数的函数通常不是所需的功能。另外,reduce
在本例中是获取一个数组
并将其转换为所需的对象的返回类型
@tyleroper no OP正在修改参数initialValue
参数。我假设在本例中,传递的字符串不会被forEach
修改,尽管我仍然不认为forEach
比reduce
更好forEach
要求您在迭代之前初始化一个空对象,在数组中迭代添加项,然后返回最终对象reduce
将这三种方法组合为一个方法。我不建议使用reduce的可能重复。为此,您正在为每个方法执行reduce
,但使用reduce
@appleapplereduce
生成一个新对象,因此函数保持纯净。调用修改传递参数的函数通常不是所需的功能。另外,reduce
在本例中是获取一个数组
并将其转换为所需的对象的返回类型
@tyleroper no OP正在修改参数initialValue
参数。我假设在本例中,传递的字符串不会被forEach
修改,尽管我仍然不认为forEach
比reduce
更好forEach
要求您在迭代之前初始化一个空对象,在数组中迭代添加项,然后返回最终对象reduce
将这三种方法合并为一种方法。