gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 21:21:10 25 4
gpt4 key购买 nike

我正在尝试用 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];
}
}
}

最佳答案

您正在向数组实例对象添加属性,而不是向数组添加元素。 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;
}
};

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

关于javascript - 对象内的数组返回长度 0,即使存在元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6349966/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com