array_count_values for JavaScript instead

前端 未结 6 1583
情歌与酒
情歌与酒 2020-12-10 20:04

I have the following PHP-script, now I need to do the same thing in JavaScript. Is there a function in JavaScript that works similar to the PHP function, I have been searchi

6条回答
  •  长情又很酷
    2020-12-10 20:30

    This should work

    function array_count_values(array) {
      var tmpArr = {};
      var key = '';
      var t = '';
      var _countValue = function(tmpArr, value) {
        if (typeof value === 'number') {
          if (Math.floor(value) !== value) {
            return;
          }
        } else if (typeof value !== 'string') {
          return;
        }
        if (value in tmpArr && tmpArr.hasOwnProperty(value)) {
          ++tmpArr[value];
        } else {
          tmpArr[value] = 1;
        }
      }
    
      for (key in array) {
        if (array.hasOwnProperty(key)) {
          _countValue.call(this, tmpArr, array[key]);
        }
    
      }
    
      return tmpArr;
    }
    console.log(array_count_values([12, 43, 12, 43, "null", "null"]));

提交回复
热议问题