Uncaught TypeError: Cannot read property '1' of null(…) in a JavaScript function

后端 未结 3 1196
青春惊慌失措
青春惊慌失措 2021-02-09 10:56

This method is part of a module; And despite the error...

Uncaught TypeError: Cannot read property \'1\' of null(…)

works to a small degree, howeve

3条回答
  •  忘掉有多难
    2021-02-09 11:21

    You can use an if statement to check if the match is null like the other answers have mentioned.

    Or you can use the logical or operator to get it onto one line and make it cleaner e.g.

    var domain = (link.href.match(/(https?:\/\/.+?)\//) || [])[1];

    You get a Type error because when the match is false the function returns null and you cannot access index 1 of null as it is not an array.

    null[1] causes a type error

    By using the logical OR operator || the domain variable is set to second condition when the first condition is falsey.

    So when the match is false the result defaults to an empty array [] and you can access any index of an empty array without getting an error and it results in undefined

    This will make domain = undefined when the match is false.

    I really wish type errors weren't a problem in JS especially with objects. I seem to have add a lot of if statement and extra code every other line just to deal with type errors.

提交回复
热议问题