[英]How to improve str check on false?
I have a varaible:我有一个变量:
public searchValue: string;
And conditions that checks if variable is not empty:以及检查变量是否不为空的条件:
const searchQuery = this.searchValue &&
this.searchValue.toString().trim().length ?
`appname[like]${this.searchValue.toString().trim()}` :
null;
if (!searchQuery) return;
How to improve this if
? if
如何改进?
searchValue
is a string, so it doesn't have a .toString()
method:) Just check for: searchValue
是一个字符串,因此它没有.toString()
方法:)只需检查:
typeof searchValue === "string" && searchValue.trim().length;
Shorter and easier to read更短更易读
I am using optional chaining to not get an error when trying to trim null/undefined我正在使用可选链接在尝试修剪 null/undefined 时不会出错
const val = this.searchValue?.trim();
const searchQuery = val.length ? `appname[like]${val}` : null;
if (!searchQuery) return; // note: return needs to be in a function
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.