什么是拿到最低或数字Array最大价值的最佳方法是什么? [英] What is the best way to get the minimum or maximum value from an Array of numbers?

查看:246
本文介绍了什么是拿到最低或数字Array最大价值的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比方说,我有一个数字数组: [2,3,3,4,2,2,5,6,7,2]

Let's say I have an Array of numbers: [2,3,3,4,2,2,5,6,7,2]

什么是找到该数组中最小或最大价值的最佳方法是什么?

What is the best way to find the minimum or maximum value in that Array?

目前,以获得最大的,我遍历数组,和重置一个变量的值,如果它大于现有的值:

Right now, to get the maximum, I am looping through the Array, and resetting a variable to the value if it is greater than the existing value:

var myArray:Array /* of Number */ = [2,3,3,4,2,2,5,6,7,2];

var maxValue:Number = 0;

for each (var num:Number in myArray)
{
    if (num > maxValue)
        maxValue = num;
}

这只是似乎并不像表现最好的方式做到这一点(我会尽量避免循环尽可能)。

This just doesn't seem like the best performing way to do this (I try to avoid loops whenever possible).

推荐答案

从别人的理论回答都是整齐的,但让我们务实。 ActionScript提供了工具,你需要让你甚至不需要写在这种情况下,循环!

The theoretical answers from everyone else are all neat, but let's be pragmatic. ActionScript provides the tools you need so that you don't even have to write a loop in this case!

首先,注意 Math.min() Math.max()可以接受任何数量的参数。此外,重要的是要理解适用()方法可用于功能的对象。它可以让你使用阵列将参数传递给函数。让我们充分利用两者的:

First, note that Math.min() and Math.max() can take any number of arguments. Also, it's important to understand the apply() method available to Function objects. It allows you to pass arguments to the function using an Array. Let's take advantage of both:

var myArray:Array = [2,3,3,4,2,2,5,6,7,2];
var maxValue:Number = Math.max.apply(null, myArray);
var minValue:Number = Math.min.apply(null, myArray);

下面是最好的部分:循环实际上是运行使用本机code(在Flash播放器),所以它比使用纯ActionScript循环搜索的最大值或最小值更快

Here's the best part: the "loop" is actually run using native code (inside Flash Player), so it's faster than searching for the minimum or maximum value using a pure ActionScript loop.

这篇关于什么是拿到最低或数字Array最大价值的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆