如何获取div内的频繁值输出? [英] How to get the frequent value output inside the div?

查看:69
本文介绍了如何获取div内的频繁值输出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

看到此文章我如何获得javascript中Array中重复次数最多的值

我是jquery的新手,我想知道如果在 id class div中声明了数组值,该如何获取数组值?

I am a newbie in jquery, I would like to know if how can I get the array values if it is declared inside an id or class div?

<p>#1 - Rate: <span class="score" id="score1"> 5</span></p>
<p>#2 - Rate: <span class="score" id="score2"> 5</span></p>
<p>#3 - Rate: <span class="score" id="score3"> 5</span></p>
<p>#4 - Rate: <span class="score" id="score4"> 5</span></p>
<p>#5 - Rate: <span class="score" id="score5"> 5</span></p>

这是输出,看起来像:

<div id="totalScore">55555</div>

我通过获得5项商品的价格来做到这一点

I did this by getting the rates of 5 items

jQuery("#totalScore").append(jQuery(".list1").text());

在上面的文章中,该值位于数组内部

In the article above the value is inside an array

var arr = [{
  values: "Number of pips"
}, {
  values: 4
}, {
  values: 4
}, {
  values: 4
}, {
  values: 5
}, {
  values: 2
}, {
  values: 6
}, {
  values: 6
}, {
  values: 5
}];



var uniqs = {};

for (var i = 0; i < arr.length; i++) {
  uniqs[arr[i].values] = (uniqs[arr[i].values] || 0) + 1;
}

var max = {
  val: arr[0],
  count: 1
};
for (var u in uniqs) {
  if (max.count < uniqs[u]) {
    max = {
      val: u,
      count: uniqs[u]
    };
  }
}

alert(max.val);

如何这样转换?通过仅获取 id ="totalScore" .list1 中的值?

How to convert it like this? By getting only the value in id="totalScore" or .list1?

推荐答案

each遍历每个.score,从而增加对象中的关联值.然后,遍历对象的entries,标识具有最大值的对象,并获取其键(通过访问条目的[0]索引):

Iterate over each .score with each, incrementing the associated value in an object. Then, iterate over the object's entries, identify the one with the maximum value, and get its key (by accessing the [0] index of the entry):

const counts = {};
$('.score').each((_, span) => {
  const num = span.textContent.trim();
  counts[num] = (counts[num] || 0) + 1;
});
console.log(
  Object.entries(counts).reduce((a, item) => (
    item[1] > a[1]
    ? item
    : a
  ), [,0])[0]
);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>#1 - Rate: <span class="score" id="score1"> 5</span></p>
<p>#2 - Rate: <span class="score" id="score2"> 5</span></p>
<p>#3 - Rate: <span class="score" id="score3"> 3</span></p>
<p>#4 - Rate: <span class="score" id="score4"> 4</span></p>
<p>#5 - Rate: <span class="score" id="score5"> 5</span></p>
<p>#6 - Rate: <span class="score" id="score6"> 4</span></p>

这篇关于如何获取div内的频繁值输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆