1

看着这个太久了,我已经把我的大脑炸了。使用以下小 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。为什么我不能动态添加属性并让任何工作正常?

4

2 回答 2

3

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

var newArray = {};
$.each(wordArray, function (ix, val) {
    if (newArray[val]) {
        newArray[val]++;
    }
    else {
        console.log('that wasnt in the array');
        newArray[val] = 1;
    }
});
于 2013-10-31T19:49:01.673 回答
2

似乎您正试图在数组上发明一个属性计数。我想你只是想要length,除非newArray是原生 Array 对象以外的东西。如果它只是 a["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
于 2013-10-31T19:45:48.907 回答