一、有时候的根据需要需要计算数组中某个元素重复出现的个数
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}
若有不足请多多指教!希望给您带来帮助!
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对找一找教程网的支持。如果你想了解更多相关内容请查看下面相关链接