一、有时候的根据需要需要计算数组中某个元素重复出现的个数

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}

若有不足请多多指教!希望给您带来帮助!

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对的支持。如果你想了解更多相关内容请查看下面相关链接

华山资源网 Design By www.eoogi.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
华山资源网 Design By www.eoogi.com