jQuery字频率计数器

时间:2013-10-31 19:37:21

标签: javascript jquery

我已经把我的大脑看得太久了。使用以下小JavaScript:

 var words = 'one two three four one two three';
        wordArray = words.split(' ');
        var newArray = [];
        var words = {};
        words.word;
        words.count;
        $.each(wordArray, function (ix, val) {
            if ($.inArray(wordArray[ix], newArray) > -1) {
                newArray[wordArray[ix]].count++;
            }
            else {
                console.log('that wasnt in the array');
                newArray.push(wordArray[ix]);
                newArray[wordArray[ix]].count = 1;
            }

        });

我收到错误cannot set property 'count' of undefined。为什么我不能动态添加属性并且有什么工作正常?

2 个答案:

答案 0 :(得分:3)

newArray应该是一个对象,其属性为单词,值为count:

var newArray = {};
$.each(wordArray, function (ix, val) {
    if (newArray[val]) {
        newArray[val]++;
    }
    else {
        console.log('that wasnt in the array');
        newArray[val] = 1;
    }
});

答案 1 :(得分:2)

好像你正试图在Array上发明一个属性计数。我认为你只需要length,除非newArray是本机Array对象以外的其他东西。如果它只是一个["word", "another"]那么你不需要做任何事情来增加长度属性它是在内部完成的

<强>更新 好的,然后确定问题是count属性newArray.length将执行您尝试使用.count

执行的操作

更新2

好的,所以看起来你想要这样做:

    var words = 'one two three four one two three';
    wordArray = words.split(' ');
    var newArray = [];
    var words = {};

    $.each(wordArray, function (ix, word ) {
        if ($.inArray(word , newArray) > -1) {
            words[word]++;
        }
        else {
            console.log('that wasnt in the array');
            words[word] = 1;
        }

    });

这会给你一个对象,其中单词是键,值是计数,如:

{ "one": 2, "four": 1} //etc