最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - conditional if for many values, better way - Stack Overflow

programmeradmin0浏览0评论

Is there a better way to deal with checking multiple values. It starts to get really busy when I have more than 3 choices.

if (myval=='something' || myval=='other' || myval=='third') {

}

PHP has a function called in_array() that's used like this:

in_array($myval, array('something', 'other', 'third')) 

Is there something like it in js or jquery?

Is there a better way to deal with checking multiple values. It starts to get really busy when I have more than 3 choices.

if (myval=='something' || myval=='other' || myval=='third') {

}

PHP has a function called in_array() that's used like this:

in_array($myval, array('something', 'other', 'third')) 

Is there something like it in js or jquery?

Share Improve this question asked Apr 8, 2011 at 19:33 jarnjarn 2631 gold badge2 silver badges8 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 6

Jquery.inArray()

Besides $.inArray, you could use Object notation:

if (myval in {'something':1, 'other':1, 'third':1}) {
   ...

or

if (({'something':1, 'other':1, 'third':1}).hasOwnProperty(myval)) {
   ....

(Note that the 1st code won't work if the client side has modified Object.prototype.)

You can avoid iterating over the array by using some kind of a hash map:

var values = {
    'something': true,
    'other': true,
    'third': true
};

if(values[myVal]) {

}

Does also work without jQuery ;)

a clean solution taken from the 10+ JAVASCRIPT SHORTHAND CODING TECHNIQUES:

longhand

if (myval === 'something' || myval === 'other' || myval === 'third') {
    alert('hey-O');
}

shorthand

if(['something', 'other', 'third'].indexOf(myvar) !== -1) alert('hey-O');
发布评论

评论列表(0)

  1. 暂无评论