I’m creating a javascript program that prompt users to input coordinates (x,y) of 2 points of each line to do further functions.
const numOfLines = parseInt(prompt("Please enter number of lines: "));
//point object
function Point(x, y)
{
this.x = x;
this.y = y;
}
let firstPoints = new Array(numOfLines);
let secondPoints = new Array(numOfLines);
for(let i = 0; i < numOfLines; i++)
{
let firstPointMessage = "Please enter the first point's coordinates x, y of line " + (i+1);
// substring input to add (x,y) to an array
let firstPoint = prompt(firstPointMessage).split(",");
//add point(x,y) to firstPoints array
let fp = new Point(parseInt(firstPoint[0]) ,parseInt(firstPoint[1]));
firstPoints.push(fp);
let secondPointMessage = "Please enter the second point's coordinates x, y of line " + (i+1);
let secondPoint = prompt(secondPointMessage).split(",");
let sp = new Point(parseInt(secondPoint[0]) ,parseInt(secondPoint[1]));
secondPoints.push(sp);
}
while(num < numOfLines)
{
document.write(firstPoints[num].x);
....further action
num++;
}
</script>
Error Cannot read properties of undefined (reading ‘x’) occurred for line document.write(firstPoints[num].x);
And firstPoints[num] actually has values when I tried to debug, but I just can’t get the value out of it to use for further action. What should I do?
Thanks
2
Answers
while(num < numOfLines) – to me seems you’re using a loop on the num variable but you never declared num as a variable anywhere in the code.
I’m a noob but I just noticed that so apologies if that sounds dumb.
You can use your i var to populate exact array cell with your wanted value.
I see that you are defining the length of the array first but you don’t need to do that, there really is no benefit, this is not C++, you have like 4GB of memory to work with.