无法将项目添加到数组中

时间:2015-04-27 06:17:09

标签: javascript

我试图在我的数组中添加一个新节点,当我调用createList()时,我认为这是一个新的空数组,所以我必须做错了,因为我得到一个list.nodes的错误未定义。

var head = createNode(null);

var list = createList();
list.nodes.push(head); // error is here, undefined array

function List(){

  this.nodes = [];
  this.addNodeToList = addNodeToList;

  function addNodeToList(data){

    var currentNode = head;
    var newNode = createNode(data);

    while(currentNode.getNextNode() != null){
      currentNode = currentNode.getNextNode();
    }

    currentNode.nextNode = newNode;

    return;
  }
}


function createNode(data){
    return new Node(data);
}

function createList(){
  return new List();
}

function Node(data){
  this.data = data;
  this.nextNode = null;
}

function createList(){
  return new Node(null);
}

1 个答案:

答案 0 :(得分:4)

您定义了两次creatList函数。 后面的定义不返回节点数组:

 function createList(){
  return new Node(null);
}

删除它,你应该没事的

编辑: 请考虑以下事项:

var a = 5;
var a = 6;
//OR
var f = function (){ alert(1)}
var f = function (){ alert(2)}

由于JS不支持函数重载,因此两次声明函数与上面的赋值具有相同的效果 - 后者隐藏了错误的