[英]Array in Node.js, how to work with it
I'm a newbye in web programming and even more in Javascript, but I'm trying to learn it as I learn Node.js, and I found this strange error... I've got this code: 我是Web编程的再见者,而Javascript则更多。但是,我在学习Node.js的同时尝试学习它,但是我发现了这个奇怪的错误……我得到了以下代码:
var structobject = function(type, title, isReplicable, isVisible) {
this._type = type;
this._title = title;
this._childElements = new Array();
this._isReplicable = isReplicable;
this._id = 0; //TODO
};
structobject.prototype.addChild = function (element) {
structobject._childElements.push(element);
};
structobject.prototype.stringify = function () {
console.log("Main element: "+this._title);
for (var i=0;i<this._childElements.length;i++) {
console.log("Child "+i+": "+this._childElements[i]._title);
}
};
structo1 = new structobject(1, "element1", true, true);
structo1.addChild(new structobject(2, "element2", true, true));
structo1.stringify();
I've got a problem here... as you may see, _childElements
is intended to be an array, and I've got the function addchild
which should add a child element into it. 我在这里遇到了一个问题...正如您可能会看到的,
_childElements
原本是一个数组,并且我有addchild
函数,该函数应该在其中添加一个子元素。
The rest of the code works, but this gives me the following error: 其余代码可以正常工作,但这给了我以下错误:
C:\Zerok\DevCenter\Structify\public_html\js\object.js:22
structobject._childElements.push(element);
^
TypeError: Cannot read property 'push' of undefined
Why does it say childElements is not defined? 为什么说未定义childElements? I tried not defining the variable, and also tried equaling it to
this._childElements = [];
我尝试不定义变量,也尝试将其等于
this._childElements = [];
but none of these ways seem to work either. 但这些方法似乎都不起作用。
What should I do so I can work dynamically with this array? 我应该怎么做才能使该阵列动态工作?
structobject._childElements.push(element);
You're trying to modify the (non-existent) _childElements
property of the Constructor function instead of the instance you created with new structobject
. 您正在尝试修改Constructor函数的(不存在的)
_childElements
属性,而不是使用new structobject
创建的实例 。
Use this
instead of structobject
on that line. 在该行上使用
this
代替structobject
。
It is conventional, in JavaScript, to use variables starting with capital letters for constructor functions. 在JavaScript中,通常使用以大写字母开头的变量作为构造函数。
var structobject = function(...) {
would be better written as: 最好写成:
var Structobject = function(...) {
or (since it is a constructor that makes objects): 或(因为它是制造对象的构造函数):
var Struct = function(...) {
or (because named functions are easier to deal with in debuggers): 或(因为命名函数更容易在调试器中处理):
function Struct (...) {
用它代替structobject
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.