在Javascript中形成trie对象

在Javascript中形成trie对象,javascript,python,trie,Javascript,Python,Trie,所以,我试图做一个trie,它将句子中的单词关联起来,而不是单词的前缀。我已经在Python中做到了这一点,如下所示: #statement trie class strie (object): def __init__(self): self.trie = {} def __repr__(self): return str(self.trie) def __str__(self): return str(self.trie) def statement(self,

所以,我试图做一个trie,它将句子中的单词关联起来,而不是单词的前缀。我已经在Python中做到了这一点,如下所示:

#statement trie

class strie (object):

def __init__(self):
    self.trie = {}
def __repr__(self):
    return str(self.trie)
def __str__(self):
    return str(self.trie)
def statement(self, phrase):
    words = phrase.split()
    current = self.trie
    while len(words) > 0:
        word = words.pop(0)
        if word in current.keys():
            current = current[word]
        else:
            current[word] = {}
            current = current[word]
我会通过测试得到结果:

       r
=> {'The': {'apple': {'is': {'red': {}, 'blue': {'or': {'yellow': {}}}}}}}
然而,当我用javascript实现这一点时,发生了一些奇怪的事情。下面是我在javascript中的实现:

    //constructs a trie formed form a single sentence as an object.
function single_trie(phrase) {
    phrase = phrase.toLowerCase();
    var trie = {};
    var words = phrase.split(" ");
    var current = trie;
    while (words.length > 0) {
        var word = words.shift();
        if(word in current) current = current[word];
        else {
            current[word] = {};
            current = current[word];
        }
    }
    return trie;
}
我得到了一个非常奇怪的结果:

    var strie = single_trie("the apple is red and blue");
console.log(strie);

{ the: { apple: { is: [Object] } } }

是什么导致我的javascript实现出现这种情况?为什么它显示[对象]?如何让它像我的python实现一样工作?

没有错误-这只是
console.log
在浏览器上的显示方式;可以展开对象以显示更多深度。数据都在那里。尝试使用
console.log(JSON.stringify(strie))
进行非交互式显示。如果您使用的是Node.js,您也可以尝试,这样可以增加最大深度–
console.dir(strie,{depth:10})
。(注意:默认值为
2
)哦,这很有效!我现在明白了。