Good afternoon,
Please, could you help me with an issue below. I am getting an error "Cannot read properties of null (reading 'split')" when trying to click "cancel" on prompt.
What all I want, to loop canceled when I cancel it in prompt.
ps.: this is a simple array with a name/surname which in future will shows via console.log
function UserList () {
let users = [];
while(true) {
users.push (prompt('Please, enter your name surname?').split(' '));
if (prompt=== null) {
alert('cancel');
}
}
}
let userList = new UserList();
You need to test whether the result of prompt()
is null
before you try to split it.
You need to break out of the loop when the user cancels, otherwise the function will never return.
Also, since you're using this as a object constructor, users
should be a property this.users
.
function UserList () {
this.users = [];
while(true) {
let response = prompt('Please, enter your name surname?');
if (response == null) {
alert('cancel');
break;
}
this.users.push (response.split(' '));
}
}