计算字符串数组中的所有事件后,结果不会显示

时间:2014-11-26 10:08:16

标签: javascript arrays json

我有一个文本字符串,我使用拆分使其成为一个数组,我想计算每个单词的所有出现,但我不能看到任何错误,但它没有显示我的HTML中的任何内容这是我想要实现的< / p>

[{"name":"you","data":[2]},
{"name":"it","data":[2]},
{"name":"that","data":[2]},
{"name":"to","data":[3]},
{"name":"strength","data":[2]}]

这是我在javascript中的代码

var counts = [];
var result = {};

var stemmed = "Example Do you really think it is weakness that yields to temptation I tell you that there are terrible temptations which it requires strength strength and courage to yield to Oscar Wilde"; 
var splitStemmed = stemmed.split(" ");

for(var i = 0; i < splitStemmed.length; i++) 
{
    for(var j = 0; j < splitStemmed.length; j++) 
    {
        if(splitStemmed[i])
        {
            if(result[splitStemmed[j]])
                result[splitStemmed[j]].data[0]++;
            else
            {
                result[splitStemmed[j]] = {name:splitStemmed[j], data:[1]};
                counts.push(result[splitStemmed[j]]);
            }
        }
    }
}

$("#show").html(counts);

3 个答案:

答案 0 :(得分:1)

结帐这个小提琴 - &gt; http://jsfiddle.net/657xpksz/2/

我想说使用forEach会更容易,因为它不涉及所有那些不同的参数,如标准for循环。

也可能不需要数组作为数据值。这是一个示例结构,上面的小提琴输出

{
    "example": 1,
    "do": 1,
    "you": 2,
    "really": 1,
    "think": 1,
    "it": 2,
    "is": 1,
    "weakness": 1,
    "that": 2,
    "yields": 1,
    "to": 3,
    "temptation": 1,
    "i": 1,
    "tell": 1,
    "there": 1,
    "are": 1,
    "terrible": 1,
    "temptations": 1,
    "which": 1,
    "requires": 1,
    "strength": 2,
    "and": 1,
    "courage": 1,
    "yield": 1,
    "oscar": 1,
    "wilde": 1
}

这种数据结构与你发布的数据结构一样容易迭代,但是如果你需要那个,可以根据需要调整上面的解决方案。

答案 1 :(得分:0)

另一种方法:

var stemmed = "Example Do you really think it is weakness that yields to temptation I tell you that there are terrible temptations which it requires strength strength and courage to yield to Oscar Wilde"; 
var splitStemmed = stemmed.split(" ");
var hash = {};

for (var i in splitStemmed)
{
    var key = splitStemmed[i];

    if (!hash[key]) hash[key] = 0;

    hash[key]++;
}

for (var word in hash)
{
    console.log('word: ' + word + ' count: ' + hash[word]);
}

答案 2 :(得分:0)

请试试。

var counts = [];
var result = {};

    var stemmed = "Example Do you really think it is weakness that yields to temptation I tell you that there are terrible temptations which it requires strength strength and courage to yield to Oscar Wilde"; 

    var splitStemmed = stemmed.split(" ");
    var resuenter code herelt={};
    for(var i=0; i< splitStemmed.length; i++)
    {
         if(result[splitStemmed[i]]==undefined){
           result[splitStemmed[i]]=1;
         }else{
           result[splitStemmed[i]]=result[splitStemmed[i]]+1;
         }
    }
    $("#show").html(JSON.stringify(result))