Skip to main content
April 23, 2009
Question

How would I better write this?

  • April 23, 2009
  • 2 replies
  • 538 views

I want to write something like this:

if(imgToLoad == 3 || imgToLoad == 4 || imgToLoad == 5)

Is there something less "wordy"?

Something like this? I am sure this is wrong, but there must be a better way?

if(imgToLoad == [3, 4, 5])

Thanks a lot for any help!

This topic has been closed for replies.

2 replies

Inspiring
April 27, 2009

It would be possible to do it like this also:

imgToLoad=4;
checkArr=[3,4,5];

if ((checkArr.join(",")).indexOf(imgToLoad)!=-1){
    trace('found it')
}

This is converting both the array and the the integer value of imgToLoad to Strings and checking for imgToLoad's  presence in the checkArr (joined) string to which the indexOf method is being applied. A value of -1 returned means it was not found in that string, so if it's not -1 then the value is in there somewhere. In this way you can add items to the checkArr and have the check work in different ways.

Doing checks like this in intensive loops would not be very efficient (it would be better to do it the 'longhand' way), but perhaps it's ok if it's not in a loop.

kglad
Community Expert
Community Expert
April 27, 2009

and you have to be careful with that because checkArr.join() is a string and you're checking for numbers.  because you're not typing your variables, as2 will let you get away with this, but that won't work if you type your variables and it won't work in as3 where you are required to type your variables.

Inspiring
April 27, 2009

kglad is right, I was doing this in a way that makes sense for as2, as well as taking advantage of as2's permissive typing.

In as3, you can use indexOf on an array, so if you are doing this in as3, you can do it like this:

var imgToLoad:uint=4;
var checkArr:Array=[3,4,5]

if ((checkArr).indexOf(imgToLoad)!=-1){
    trace('found it')
}

kglad
Community Expert
Community Expert
April 23, 2009

in general, that's about the best you can do.

in the case you cited you can to do a little better if imgToLoad is an integer:

if(imgToLoad>=3 && imgToLoad<=5)