So I am having a problem with deleting items from an array while in a for loop
var div = document.querySelector('div');
var array = [
"iPad",
"iPod",
"iPhone"
];
for (let i = 0; i < array.length; i++) {
let p = document.createElement('p');
p.textContent = array[i];
div.appendChild(p);
p.onclick = function() {
array.splice(array.indexOf(this, 1));
this.remove();
console.log(array);
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>repl.it</title>
</head>
<body>
<div>
</div>
</body>
</html>
So the problem is that when I click on an item to delete it, it doesn't delete that specific one. No matter which one I click on, it deletes starting from the bottom ("iPhone" to "iPod" to "iPad").
Visually, it deletes the right one but when I go to the console I can see that it deletes from the bottom up. Any help would be so very much appreciated.