Posted in Javascript onJanuary 18, 2019
一、有时候的根据需要需要计算数组中某个元素重复出现的个数
var arr = ["apple","orange","apple","orange","pear","orange"];
计算出来重复出现的元素个数:{apple: 2, orange: 3, pear: 1}
二、代码实现
//统计一个数组中有多少个不重复的单词: // 不用reduce时: var arr = ["apple","orange","apple","orange","pear","orange"]; function getWordCnt(){ var obj = {}; for(var i= 0, l = arr.length; i< l; i++){ var item = arr[i]; obj[item] = (obj[item] +1 ) || 1; } return obj; } console.log(getWordCnt());//{apple: 2, orange: 3, pear: 1} // 用reduce时: var arr = ["apple","orange","apple","orange","pear","orange"]; function getWordCnt(){ return arr.reduce(function(prev,next){ prev[next] = (prev[next] + 1) || 1; return prev; },{}); } console.log(getWordCnt());//{apple: 2, orange: 3, pear: 1}
补充知识点:
若查询对象中某个属性没有,可自行为其添加
var muziObj = {}; muziObj['name'] = 'muzidigbig'; muziObj.age = 21; console.log(muziObj)//{name: "muzidigbig", age: 21}
若有不足请多多指教!希望给您带来帮助!
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对三水点靠木的支持。如果你想了解更多相关内容请查看下面相关链接
js根据需要计算数组中重复出现某个元素的个数
- Author -
muzidigbig声明:登载此文出于传递更多信息之目的,并不意味着赞同其观点或证实其描述。
Reply on: @reply_date@
@reply_contents@