I checked some question with similar issues but could not cope with mine where I have a file.js:
'use strict'
function singlyLinkedList() {
if (this ) {
this.head = null
}
}
singlyLinkedList.prototype.append = function(value) {
let node = {
data: value,
next: null
}
if( !this.head ) {
this.head = node
} else {
let pointer = this.head
while( pointer ) {
pointer = pointer.next
}
pointer.next = node
}
}
Which I call from index.html:
<!DOCTYPE html>
<html>
<head>
<title> Test </title>
<meta charset="UTF-8">
<script src="file.js"></script>
</head>
<body>
<script>
let linkedList = singlyLinkedList()
let integersArray = [1, 22, 333, 4444]
integersArray.forEach(element => linkedList.append(element))
</script>
</body>
</html>
Navigating this HTML file using Chrome browser and checking the console, shows this error message:
Uncaught TypeError: Cannot read property 'append' of undefined
How to fix this?
Update:
The second issue I have with this (maybe a separate question?) is that if I write:
function singlyLinkedList() {
this.head = null
}
I get this error message:
Uncaught TypeError: Cannot set property 'head' of undefined
few things you need to take care of,
new
keyword to create an instance of 'singlyLinkedList'while
loop is not correct. it should be while( pointer.next )
check below version,
//create a `file.js` file and put this code inside that. running this code snippet on stackoverflow util wont work as you need a separate `file.js`
'use strict';
function singlyLinkedList() {
this.head = null;
}
singlyLinkedList.prototype.append = function(value) {
let node = {
data: value,
next: null
};
if( !this.head ) {
this.head = node
} else {
let pointer = this.head;
while( pointer.next ) { //check this
pointer = pointer.next
}
pointer.next = node
}
};
<!DOCTYPE html>
<html>
<head>
<title> Test </title>
<meta charset="UTF-8">
<script src="file.js"></script>
</head>
<body>
<script>
let linkedList = new singlyLinkedList(); // check this
let integersArray = [1, 22, 333, 4444];
integersArray.forEach(element => linkedList.append(element));
console.log('linkedList: ', linkedList);
</script>
</body>
</html>
it will log something like,
And I strongly believe you need to use a new
keyword for creating an instance of singlyLinkedList
function as you want to use the benefit of the prototype
concept