简体   繁体   中英

Shorthand for “If greater than, then equal to” in Acttionscript?

Is there a shorthand method to write the following code? Often in games we want to make sure certain things dont leave a boundary, or more generally, we want to stop an index of an array from going beyond the bounds of an array. I've always written it this way, but am wondering if there is a shorthand in Actionscript, Java, or C#

In Actionscript:

index++;
if (index > array.length - 1) index = array.length - 1;

as far as I can tell, there is no operator that accomplishes this, though perhaps I am mistaken. I know the ternary operator is similar if (condition) ? value if true : value if false if (condition) ? value if true : value if false

您可以使用Math.min

index = Math.min (index+1, array.length-1);

For the generic condition of if (condition) set variable (as opposed to your specific case) you could use the following:

variable = (condition) ? (set if true) : (set if false)

In your case, this turns in to:

index = index > array.length - 1 ? index = array.length - 1 : index;

It works in Java, Actionscript, and C#.

If your code looks like this (C#):

index++;

if (index > array.length - 1)
    index = array.length - 1;

You're doing the equality testing no matter what anyway, so why not do it before the assignment?

if (index < array.Length)
    index++;

I don't know of any shorter method in C#, but you could write your own extension to use, so you don't have to copy/paste the check throughout your code:

public static class ArrayExtensions
{
    // Returns the index if it falls within the range of 0 to array.Length -1
    //  Otherwise, returns a minimum value of 0 or max of array.Length - 1
    public static int RangeCheck(this Array array, int index)
    {
        return Math.Max(Math.Min(index, array.Length - 1), 0);
    }
}

To use it:

var index = yourArray.RangeCheck(index);

请尝试以下操作,它也将更加高效,因为您不会进行不必要的增加:

if( index < array.length ) index++;

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