简体   繁体   English

比较JavaScript中的两个字符串

[英]compare two strings in javascript

I would like to compare two strings and decide if they are not equal. 我想比较两个字符串并确定它们是否相等。 I have the code below, but it seems that it is not returning what I want, is this correct? 我有下面的代码,但似乎它没有返回我想要的东西,这是正确的吗?

if ((current.request.requested_for != reviewer) && (current.request.requested_for != approver)) {
     return 'Yes';
  }
  return 'No';

} }

Here reviewer and approver, are some strings that I have declared in lines prior to the if conditions. 这里的审阅者和批准者是我在if条件之前的行中声明的一些字符串。 Basically, my question here is to know if I should use != to check if 2 strings are not equal. 基本上,我的问题是知道是否应该使用!=检查2个字符串是否相等。

Thanks 谢谢

Assuming that you have strings in the variables reviewer, approver and the object current.request.requested_for, you can just compare two strings with === which compares type and value. 假设您在变量审阅者,批准者和对象current.request.requested_for中包含字符串,则只需将两个字符串与===进行比较,即可比较类型和值。 If you compare with ==, you are just comparing the value, there are more reasons about == is returning true for '2' == 2, visit this . 如果与==进行比较,则只是在比较值,还有更多的理由使==对于'2'== 2返回true,请访问this

So, your code could be more declarative and simpler 因此,您的代码可以更具声明性和更简单

(...)
    const SEARCH = [reviewer, approver];
    return SEARCH.includes(current.request.requested_for)
(...)

If your are not using latest javascript do not worry, you could achieve the same with an array declaration and the indexOf() method . 如果您不使用最新的javascript,请不要担心,可以通过数组声明indexOf()方法实现相同的效果。 They are the former way of the code. 它们是代码的前一种方式。

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

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