为什么空结果会冻结脚本以及如何避免它

Why a null result is freezing the script and how to avoid it?

本文关键字:何避免 脚本 结果 冻结 为什么      更新时间:2023-09-26

当我使用以下代码时:

if(string.match(/td>0/g).length == 8) {
    /*Do something*/
}

并且没有匹配/td>0/,它会返回一个null结果,阻止下面的脚本执行。

我想知道为什么代码冻结,以及如何避免它并找到.match()的解决方案或替代方案?

您可以先添加一个null检查 -

if(string.match(/td>0/g) != null && string.match(/td>0/g).length == 8) {
    /*Do something*/
}

试试这个(更多推荐):

var matching=string.match(/td>0/g);
if( matching != null && matching.length === 8) {
    /*Do something*/
}

使用 === 而不是 ==

在检查长度之前,您需要进行空检查。我会先做比赛,然后检查

var result = string.match(/td>0/g);
if (result && result.length) {}

或使用 or 来捕获空值

if( (string.match(/td>0/g)||"").length ) {}