javascript - Can a variable equal two things in an if statement? - Stack Overflow

I've tried looking around on here for this, but I'm not quite sure whether I'm phrasing

I've tried looking around on here for this, but I'm not quite sure whether I'm phrasing it correctly.

if (a=="something" && a=="Something") {
//some code
}
else {
// some code
}

Can the a variable in this statement equal both "something" and "Something" with the capital S. I've tried just using "something" without the capital, however this doesn't work.

I've tried looking around on here for this, but I'm not quite sure whether I'm phrasing it correctly.

if (a=="something" && a=="Something") {
//some code
}
else {
// some code
}

Can the a variable in this statement equal both "something" and "Something" with the capital S. I've tried just using "something" without the capital, however this doesn't work.

Share Improve this question asked Mar 18, 2013 at 18:21 user2166577user2166577 4
  • No and use === instead of == if it is a string. There may be a problem with incorrect string parsing. – theshadowmonkey Commented Mar 18, 2013 at 18:22
  • a can't be equal to both "something" and "Something", which is what you are testing for, that if condition will always be false. What are you trying to do? – Chris Cherry Commented Mar 18, 2013 at 18:24
  • The variable itself cant equal both "something" and "Something". But, it can equal "something" OR "Something" if (a=="something" || a=="Something") – user1120369 Commented Mar 18, 2013 at 18:25
  • in its most basic form jsfiddle/Rd5Ly – user2166577 Commented Mar 18, 2013 at 18:28
Add a ment  | 

4 Answers 4

Reset to default 3

No, but just use toLowerCase:

if (a.toLowerCase() === 'something') {
    // something here
}

This will never work, as a can never hold 2 Strings at the same time.

What you are eventually looking for is ||

if (a=="something" || a=="Something") {
//some code
}
else {
  // some code
}

a logical OR, which means that a can either be "something" OR "Something"

What you are doing right now is checking if a is "something" AND "Something" at the same time (which is not possible)

Not at the same time. You probably want an OR.

  if(a === "something" || a === "Something"){

What you can do is check your variable ignoring case like this :

a.toUpperCase() === "SOMETHING";

Note this will work with "SoMeThinG" as well (and every bination of case, look here for more about case insensitive parison)
And as other answers says : You are probably looking for || operator.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745050438a4608353.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信