我看着这个问题已经花了很长时间了。使用以下小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。为什么我不能动态添加属性并且一切正常?

最佳答案

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

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

关于javascript - jQuery单词频率计数器,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19715187/

10-09 15:10