Typescript:对象可能为 null
如何在 VSCode 中避免‘对象可能为 null’,即使代码运行正常
let url = 'https://test.com/test/varstring/stringtoextract?id=test3'
let regex = /https:\/\/test.com\/test\/varstring\/.+\/(.+)?.+/
var match = regex.exec(url);
alert(match[1]);
答案#1
如果你确定,请使用非空断言操作符 !:
alert(match![1]);
当然,if 语句也能做到这一点:
if (match) {
alert(match[1]);
}
