对象内的数组返回长度 0,即使存在元素

发布于 2024-11-15 10:56:59 字数 1654 浏览 3 评论 0原文

我正在尝试用 Javascript 实现 Trie,这很容易,但我的对象似乎遇到了障碍。

节点的结构如下:

var node = {
    children: []
}

Children 是由字符串中的字母映射的节点数组。所以字符串“Test”看起来像这样:

root = {
  children: [
      't' => {
          children: [
              'e' => {
                   children: [
                       's' => {
                            children: [
                                 't' => {
                                      children: []
                                  }
                            ]
                        }
                   ]
               }
          ]
      }
  ]
};

所以每个子数组的长度应该为 1,但是如果执行类似 alert(this._root.children.length); 的操作,我会得到零。对于为什么会发生这种情况有什么想法吗?

这是我的其余实现:

function Trie() {
    this._root = {
        children: []
    };
}

Trie.prototype = {

    //restore constructor
    constructor: Trie,

    add: function (str){
        var curr = this._root,
            prev,
            currchar;
        // For each character in the string
        for(var i = 0, j = str.length; i < j; i++) {
            // Insert only lowercase letters for efficiency
            currchar = str.toLowerCase().charAt(i);
            prev = curr;
            curr = prev.children[currchar];
            // Traverse until we hit a non-existant node
            if(typeof(curr) == "undefined") {
                // Make a new node
                prev.children[currchar] = {
                    children: []
                };
                curr = prev.children[currchar];
            }
        }
    }

I am trying to implement a Trie in Javascript, which is easy enough but I seem to have hit a road block with my object.

The nodes are structured as follows:

var node = {
    children: []
}

Children is an array of nodes that is mapped by a letter in a string. So the string "Test" would look like this:

root = {
  children: [
      't' => {
          children: [
              'e' => {
                   children: [
                       's' => {
                            children: [
                                 't' => {
                                      children: []
                                  }
                            ]
                        }
                   ]
               }
          ]
      }
  ]
};

So each children array should have a length of 1, but if do something like alert(this._root.children.length); I get zero. Any thoughts on why this is happening?

Here is the rest of my implementation:

function Trie() {
    this._root = {
        children: []
    };
}

Trie.prototype = {

    //restore constructor
    constructor: Trie,

    add: function (str){
        var curr = this._root,
            prev,
            currchar;
        // For each character in the string
        for(var i = 0, j = str.length; i < j; i++) {
            // Insert only lowercase letters for efficiency
            currchar = str.toLowerCase().charAt(i);
            prev = curr;
            curr = prev.children[currchar];
            // Traverse until we hit a non-existant node
            if(typeof(curr) == "undefined") {
                // Make a new node
                prev.children[currchar] = {
                    children: []
                };
                curr = prev.children[currchar];
            }
        }
    }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

香草可樂 2024-11-22 10:56:59

您正在向数组实例对象添加属性,而不是向数组添加元素。 length 属性仅包含数组元素,不包含数组实例对象的属性。

var a = [23, 42];
console.log(a.length); // 2
a['foo'] = 'bar';
console.log(a.length); // 2
a[2] = 1337;
console.log(a.length); // 3

编辑:
您可以像这样构造节点:

var node = {
    children: {},
    length: function () {
        var i = 0;
        var k;

        for (k in this.children) {
            if (this.children.hasOwnProperty(k)) {
                i++;
            }
        }
        return i;
    }
};

当然,这是低效的。您应该在其原型上定义一个带有 length 方法的 Node 类。或者,定义一个 add 方法来更新 length 属性。

You are adding properties to the array instance object, not elements to the array. The length property only includes array elements, not properties on the array instance object.

var a = [23, 42];
console.log(a.length); // 2
a['foo'] = 'bar';
console.log(a.length); // 2
a[2] = 1337;
console.log(a.length); // 3

EDITED:
You could instead structure the nodes like this:

var node = {
    children: {},
    length: function () {
        var i = 0;
        var k;

        for (k in this.children) {
            if (this.children.hasOwnProperty(k)) {
                i++;
            }
        }
        return i;
    }
};

This is inefficient, of course. You should instead define a Node class with the length method on its prototype. Alternatively, define an add method that updates the length property.

岁月蹉跎了容颜 2024-11-22 10:56:59

我认为问题在于您使用 javasrcipt 数组作为关联数组(如其他语言中所示)。在 JavaScript 中,“关联”数组是没有长度属性的对象。普通数组具有数字索引。

与问题无关,但您可能会发现很有用。

I think that the problem is that you use a javasrcipt array as an associative array (as found in other languages). In javascript "associative" arrays are objects that don't have a length property. Normal arrays have numeric indices.

Irrelevant to the question but you might find this useful.

千紇 2024-11-22 10:56:59

也许您想要的

str.toLowerCase().charCodeAt(i)

不是

str.toLowerCase().charAt(i)

If str is "f1",您要添加到子数组的属性是 "f""1" 应该生成一个属性名为 f 且长度为 0 的数组,以及另一个长度为 2 且属性 1.

要仅获取数字属性,您应该确保属性名称是有效的数组索引——可用 31 位表示的正整数。

通过使用 charCodeAt 而不是 charCode,您将获得属性名称 10249 而不是 ” f"1

Maybe you want

str.toLowerCase().charCodeAt(i)

instead of

str.toLowerCase().charAt(i)

If str is "f1", the properties you're adding to the children array are "f" and "1" which should cause an array with property named f and length 0, and another child array with length 2 and property 1.

To get only numeric properties, you should make sure your property names are valid array indices -- positive integers representable in 31 bits.

By using charCodeAt instead of charCode, you would get the property names 102 and 49 instead of "f" and 1.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文