如何使用javascript检测值是否为null?

如何使用javascript检测值是否为null?,javascript,regex,match,Javascript,Regex,Match,从API接收数据并使用match()查找tecto在某些情况下,match()不正确,然后为null,我收到以下错误: 未捕获(承诺中)类型错误:无法读取null的属性“1” 我尝试验证match()是否为null,数据是否为空字符串,但它仍然返回相同的错误 如何消除控制台中的错误 我的代码: let text = jsonDesc.plain_text; dataOfProduct.description.desc = text;

从API接收数据并使用match()查找tecto在某些情况下,match()不正确,然后为null,我收到以下错误:

未捕获(承诺中)类型错误:无法读取null的属性“1”

我尝试验证match()是否为null,数据是否为空字符串,但它仍然返回相同的错误

如何消除控制台中的错误

我的代码:

            let text = jsonDesc.plain_text;

            dataOfProduct.description.desc = text; 

            const product = 'Producto:';
            let resultProduct = text.match(new RegExp(product + '\\s(\\w+)', 'i'))[1];

            const model = 'Modelo:';
            let resultModel = text.match(new RegExp(model + '\\s(\\w+)', 'i'))[1];

            if( resultProduct !== null && resultProduct.length > 1){
                dataOfProduct.description.title = resultProduct;
            } else{
                dataOfProduct.description.title = ''
            }

            if( resultModel !== null && resultModel.length > 1 ){
                resultModel.description.model = resultModel;
            } else{
                resultModel.description.model = ''
            }    

您的问题是,如果
text
string与正则表达式不匹配,则match函数返回null,该函数没有[1]字符。在尝试获取[1]之前,必须将匹配结果存储在变量中,并确定该结果是否为null

let resultProduct = text.match(new RegExp(product + '\\s(\\w+)', 'i'));
if (resultProduct != null) {
  resultProduct = resultProduct[1];
}
如果匹配项发现了什么,那么代码将进入If并从中获取[1]。如果没有,那么它是空的,不进入If,下一个If-then检查resultProduct是否为空


对于产品匹配和型号匹配,您都需要这样做

问题在于,当匹配本身为空时,您试图访问匹配的索引1。您需要引入一个中间变量,然后在访问它的属性之前检查它是否为null。谢谢。但在此之前,我只能验证文本是否与null不同,因为我需要进行匹配以验证是否找到常量乘积的单词,因此我不知道如何在匹配之前进行验证@乔纳森·威尔逊