简体   繁体   English

冗余 if 语句?

[英]Redundant if statement?

Is the if statement in the following example redundant?以下示例中的if语句是否多余?

if (str[0] === ' ') {
  str = str.trimStart()
}

It seems unnecessary to me since trimStart() does not seem to have any negative effect on a string without a space at the beginning.这对我来说似乎没有必要,因为trimStart()似乎对开头没有空格的字符串没有任何负面影响。 Additionally, if the string does have a space at the beginning, you are running twice as many operations as needed.此外,如果字符串的开头确实有一个空格,则您将根据需要运行两倍的操作。

Is the if statement ever necessary in situations like the one above?在上述情况下是否需要if语句?

Given the edited code, there's one situation where the if statement could be useful - if the string starts with a newline (which counts as whitespace, and would be trimmed), not a plain space.鉴于编辑过的代码,在一种情况下if语句可能很有用 - 如果字符串以换行符开头(这算作空格,并会被修剪),而不是一个普通的空格。 For example:例如:

 const parseStr = (str) => { if (str[0] === ' ') { str = str.trimStart() } console.log(str.length); }; parseStr('\\nfoo'); parseStr(' foo'); parseStr('foo');

If trimStart was called unconditionally, the newline would be trimmed regardless:如果无条件调用trimStart ,则无论以下情况如何,都将修剪换行符:

 const parseStr = (str) => { str = str.trimStart() console.log(str.length); }; parseStr('\\nfoo'); parseStr(' foo'); parseStr('foo');

The if is not necessary, but you should save the trimmed value somewhere, like if不是必需的,但您应该将修剪后的值保存在某处,例如

str = str.trimStart();

-- Edit -- - 编辑 -

"Is the 'if' ever necessary...?" “‘如果’有必要吗……?”

The test that you are doing in the original is redundant.你在原文中做的测试是多余的。 But you might want to check that str has a value and/or check that this value is a string before calling trimStart(), like但是您可能想在调用 trimStart() 之前检查 str 是否具有值和/或检查该值是否为字符串,例如

if (str && typeof str === 'string') ...

The if block isn't necessary since the trimStart function won't have any effect if there is not space in the beginning of the string. if 块不是必需的,因为如果字符串开头没有空格,则trimStart函数将没有任何效果。 Having the if statement does not have any effect over it and wouldn't really have any real performance benefits either.拥有 if 语句对它没有任何影响,也不会真正带来任何真正的性能优势。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM