javascript - 链表实现上的 toString 方法在 js 中不起作用

标签 javascript

我正在完成 Cracking the Coding Interview,我想我会在 JS 5 中实现所有数据结构。谁能向我解释为什么我的 toString 方法不起作用?

谢谢!

    function Node(data) {
    	this.next = null;
      this.data = data;
    }
    
    Node.prototype.appendToTail = function(data) {
    	var end = new Node(data);
      var n = this;
      while (n.next != null) {
      	n = n.next;
      }
      n.next = end;
    }
    
    Node.prototype.toString = function(head) {
    	
    	console.log(head)
    
    	if (head == null) {
      	return ""
      } else {
    	  return head.data.toString() + "-> " + head.next.toString();
      }
    	
    }
    
    var ll = new Node(1);
    ll.appendToTail(3);
    ll.appendToTail(4);
    
    console.log(ll.toString())

最佳答案

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

Node.prototype.appendToTail = function(data) {
  var end = new Node(data);
  var n = this;
  while (n.next != null) {
    n = n.next;
  }
  n.next = end;
};

Node.prototype.toString = function() {
    var returnValue = String(this.data);
    if (this.next) {
        returnValue = returnValue + "-> " + String(this.next); 
    }
    return returnValue;
};

var ll = new Node(1);
ll.appendToTail(3);
ll.appendToTail(4);

console.log(String(ll))

或者完全避免这类问题,不使用prototype、class、this、call等

关于javascript - 链表实现上的 toString 方法在 js 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46865448/

相关文章:

javascript - 重复对象中的 Array.push()、不正确或无法理解

javascript - 使用javascript函数检索隐藏文本值对象HTMLinputElement错误

javascript - 使用 GET 将复杂的 JS 对象从 Angular 传递到 C# WebApi

javascript - React Navigation 5,获取最接近的父导航器名称

javascript - 问题设置回调结果等于对象属性(node-tesseract)

javascript - 打开数据库卡住

javascript - 如何从 Javascript Microsoft Dynamics 调用操作

javascript - 如何使最后一行表现正常,直到到达视口(viewport)末尾,然后在 AgGrid 中充当 float 行?

Javascript--统计每个字符串出现的频率并从大到小打印出来

javascript - Vuetify v-alert 在 react 属性更新时不显示