Home > Blockchain >  TypeError: Cannot read properties of undefined (reading '0'). in javascript
TypeError: Cannot read properties of undefined (reading '0'). in javascript

Time:01-10

why this error is appearing

my code is ,

/**
 * @param {number[][]} points
 * @return {number}
 */
var maxPoints = function(points) {
    n=0
    for(let i=0;i<=points.length;i  ){
    let x=points[i]
    const y=points[i 1]
    let dx=y[0]-x[0]
    let dy=y[1]-x[1]
    m=dy/dx
    b = y[1]-m*y[0]
    newy=m*y[0] b
        if(newy==y[1]){
            n  
        }
        console.log(y)
    }
    return(n)
};

Error

Line 10 in solution.js
    let deltax=y[0]-x[0]
                ^
TypeError: Cannot read properties of undefined (reading '0')
    Line 10: Char 17 in solution.js (maxPoints)
    Line 31: Char 19 in solution.js (Object.<anonymous>)
    Line 16: Char 8 in runner.js (Object.runner)
    Line 22: Char 26 in solution.js (Object.<anonymous>)
    at Module._compile (node:internal/modules/cjs/loader:1101:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
    at node:internal/main/run_main_module:17:47

Question is find the max number of points to draw a straight line from the given array of points how to solve this error

CodePudding user response:

I'm not clear on your overall goal here, or the expected structure of points, but I can see the cause of the specific error.

Let's say the array points has 4 items. Your loop continues while i <= points.length, i.e. <= 4 in our example. However, arrays are zero-indexed in JavaScript, so i[4] will be undefined.

Adding to that, you assign y to points[i 1]. In our example, when i is 3, i 1 will be 4 - so y will be undefined - when you attempt to access y[0] here, y will be undefined and not an array, so accessing [0] will fail.

CodePudding user response:

change loop condition to i<points.length

  • Related