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

从数字数组中获取最小值或最大值的最佳方法是什么?

SEO心得admin45浏览0评论
本文介绍了从数字数组中获取最小值或最大值的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

假设我有一个数字数组:[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() 可以接受任意数量的参数.此外,了解可用于 Function 对象的 apply() 方法也很重要.它允许您使用 Array 将参数传递给函数.让我们充分利用两者:

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);

最好的部分是:循环"实际上是使用本机代码(在 Flash Player 中)运行的,因此它比使用纯 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.

发布评论

评论列表(0)

  1. 暂无评论