简体   繁体   中英

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. Basically, my question here is to know if I should use != to check if 2 strings are not equal.

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. If you compare with ==, you are just comparing the value, there are more reasons about == is returning true for '2' == 2, visit 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 . They are the former way of the code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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