JavaScript:计算字符串中特定整数的实例

时间:2016-04-27 19:22:46

标签: javascript jquery html

好的,所以我在div中有一堆数字,让我们说类似......

<div id="countme">7, 5, 6, 0, 3, 0, 5, 3, 3, 2, 8</div>

我想使用JavaScript返回...

  • 具体数字和
  • div中出现该号码的次数

输出示例:“(2,0),(1,2),(3,3),(2,5),(1,6),(1,7),(1,8)”< / p>

解释:零出现两次,两次出现一次,三次出现三次等等......

我尝试了以下内容......

var str = document.getElementById('countme').innerText;
var match = str.match(/7/g);
var match1 = str.match(/5/g);
alert(match.length);
alert(match1.length);

但是我需要它来显示它搜索到的数字,我需要一切都在一个警报中。

有什么想法吗?

谢谢! :)

4 个答案:

答案 0 :(得分:1)

JSBIN:https://jsbin.com/tesezoz/1/edit?js,console

var str = "7, 5, 6, 0, 3, 0, 5, 3, 3, 2, 8";

// first get the numbers
var m = str.split(', ').map(Number);

// turn it into an object with counts for each number:

var c = m.reduce(function(a, b) {
  a[b] = ++a[b] || 1;
  return a;
}, {});

// now you have an object that you can check for the count
// which you can alert... its the c variable

答案 1 :(得分:0)

这是答案

var str    = document.getElementById('countme').innerText;
var array  = JSON.parse("[" + str+ "]");
var counts = {};
array.forEach(function(x) { counts[x] = (counts[x] || 0) + 1; });
console.log(counts);

答案 2 :(得分:0)

试试这个......

&#13;
&#13;
var str = "7, 5, 6, 0, 3, 0, 5, 3, 3, 2, 8";
str = str.replace(/\s/g, "");
str = str.split(",");

var result = {};

str.forEach(function(value) {
    if (result[value]) {
        result[value]++;
    }
    else {
        result[value] = 1;
    }
});

var output = "";

for(value in result) {
    output += (output == "" ? "" : ",") + "(" + value + "," + result[value] +")";
}

alert(output);
&#13;
&#13;
&#13;

它拆分字符串并删除任何空格,因此你留下了一个数组(并且不假设分隔符是一致的)。

然后创建一个表示每个值和计数的对象。

它最终将其转换为输出,类似于示例中的输出。

答案 3 :(得分:0)

我认为这几乎和你一样有效。它还可作为一般计数唯一匹配方法:

var testString = document.getElementById('countme').innerText;
count = {}; 
var regX = /(\d+)/g;
var res;
while (res = regX.exec(testString )) {
    count[res[0]] = (count[res[0]] !== undefined ? ++count[res[0]] : 1)
};