我正在使用原型在javascript中实现一个简单的链接列表。我遇到了一些我不太了解的事情 -
var Node = function( value ) {
this.value = value;
this.next = null;
};
var List = function( head ) {
this.head = null;
};
List.prototype.insert = function( value ) {
if ( this.head === null ) {
this.head = new Node( value );
} else {
var aNode = this.head;
console.log( 'same: ' + (aNode === this.head)); // prints true
while ( aNode.next !== null ) {
aNode = aNode.next;
}
var node = new Node( value );
aNode.next = node;
console.log( 'Head: ' + this.head.value ); //prints 1
console.log( 'Node: ' + aNode.value ); //prints 2,3,4
}
};
var aList = new List();
aList.insert( 1 );
aList.insert( 2 );
aList.insert( 3 );
aList.insert( 4 );
如果this.head和aNode共享引用,则将aNode更改为aNode.next不会更改this.head。有人可以解释原因吗?我是原型的新手。
答案 0 :(得分:2)
由于操作顺序。你需要括号:
console.log( 'same: ' + (aNode === this.head))
// ---------------------^-------------------^
没有它们,它实际上是
console.log( ('same: ' + aNode) === this.head)
...(当然,这是假的)因为+
的{{3}}比===
。 if (a + 5 === 6)
为a
时1
为真的原因相同。
答案 1 :(得分:0)
在YEAR
中,它首先评估console.log
字符串和same
的串联,然后与aNode
进行比较:
将其更改为:
this.head
或:
console.log( 'same:' + (aNode === this.head))
答案 2 :(得分:0)
这应该可以解决问题......让我知道。
var chores = new List("chores");
chores.add("Mow lawns.");
// CODE
<!DOCTYPE html>
<html>
<head>
<script>
//LIST (OBJECT CONSTRUCTOR)
var List = function(title){
this.title = title;
this.datetime = new Date();
this.items = [];
};
//LIST (OBJECT METHOD - ADD)
//ALL OBJECTS CREATED FROM THE LIST OBJECT CONSTRUCTOR ABOVE INHERIT THIS METHOD
List.prototype.add = function(val){
this.items.push(val);
};
//CREATE NEW LIST OBJECT CALLED (CHORES)
var chores = new List("chores");
//INPUT DATA USING LIST METHOD ADD, WHICH OBJECT CHORES INHERITED WHEN IT WAS INSTANTIATED (CREATED)
chores.add("Mow lawns.");
chores.add("Make dinner.");
chores.add("Drive to the store.");
//VIEW OUTPUT
console.log(chores);
console.log(chores.items);
console.log(chores.items[0]);
console.log(chores.items[1]);
console.log(chores.items[2]);
</script>
</head>
<body>
</body>
</html>