空检查返回语句 [英] Null check in the return statement

查看:55
本文介绍了空检查返回语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

data.req 中的值为空时, data.req.toLowerCase()抛出错误.如何检查

When I have a null value in data.req, data.req.toLowerCase() is throwing an error. How can I check for a condition like

if(data.req === null) {
    //do nothing
} else { 
    data.req.toLowerCase().indexOf(searchTerms.req) !== -1
}

//我应该如何在下面提到的return语句中仅对data.req检查null?

// How should i check for null for only data.req in the below mentioned return statement ?

return data.client.toLowerCase().indexOf(searchTerms.client) !== -1
    && data.req.toLowerCase().indexOf(searchTerms.req) !== -1;

//样本数据

Data: [{req: "test", client: "client_01"},
{req: "now_test_01", client: "sample client"},
{req: "test", client: "client_01"},
{req: null, client: "sample client"},
{req: null, client: "client_01"},
{req: "now_test_018", client: "sample client"}]

推荐答案

如果 data.req null ,则可以使用默认值.

You could use a default value, if the data.req is null.

(data.req || '').toLowerCase().indexOf(searchTerms.req) !== -1

或使用ES6

(data.req || '').toLowerCase().includes(searchTerms.req)

这篇关于空检查返回语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆