as3 随机数组 - 随机化数组 - actionscript 3 [英] as3 random array - randomize array - actionscript 3

查看:43
本文介绍了as3 随机数组 - 随机化数组 - actionscript 3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用 actionscript 3 随机化数组?

How do you randomize an array using actionscript 3?

推荐答案

有一个使用 Array.sort() 函数的简短版本:

There is a short version using Array.sort() function:

var arr : Array = [0,1,2,3,4,5,6,7,8,9];

function randomize ( a : *, b : * ) : int {
    return ( Math.random() > .5 ) ? 1 : -1;
}

trace( arr.sort( randomize ) );

如果你没有得到足够"的随机性,你可以排序两次:)

If you don't get "enough" randomness you can sort twice :)

EDIT - 逐行解释:

对于Array 类方法sort(),您不仅可以传递诸如Array.CASEINSENSITIVE、Array.DESCENDING 等排序选项,而且还有您自己的自定义比较函数引用(回调),它接受两个参数(要比较的数组中的两个元素).来自 AS3 文档:

For Array class method sort() you can pass not only sort options like Array.CASEINSENSITIVE, Array.DESCENDING and so on but also your own custom compare function reference (a callback) that accepts two parameters (two elements from array to compare). From AS3 documentation:

比较函数应该接受两个参数进行比较.给定元素 A 和 B,compareFunction 的结果可以是负值、0 或正值:

A comparison function should take two arguments to compare. Given the elements A and B, the result of compareFunction can have a negative, 0, or positive value:

  • 负返回值指定 A 在排序序列中出现在 B 之前.
  • 返回值 0 指定 A 和 B 具有相同的排序顺序.
  • 正返回值指定 A 在排序序列中出现在 B 之后.

注意:比较函数参数可能是类型化的(如果你的数组是类型化的)并且有你想要的任何名称,例如:

Note: compare function parameters might be typed (if your array is typed) and have any name you want eg.:

function compareElements ( elementA : SomeClass, elementB : SomeClass ) : int;

当您需要按特殊属性对数组元素进行排序时,此方法非常有用.在随机化情况下 compareFunction 随机返回 -1, 01 并使数组元素切换它们的位置(索引).我发现更好的随机化(在我的主观和数学上未经测试的观点)是方法只返回 -11.还要记住,带有自定义比较功能的排序功能不会按顺序比较元素 因此在某些特殊情况下,随机化结果可能与您预期的不同.

This method is very useful when you need to sort array elements by their special properties. In randomization case compareFunction randomly returns -1, 0 or 1 and makes array elements to switch their places (indices). I have found that better randomization (in my subjective and mathematically untested opinion) is when method returns only -1 and 1. Also have in mind that sorting function with custom compare function doesn't compare elements sequentially so in some special cases randomization results may differ from what you might expect.

这篇关于as3 随机数组 - 随机化数组 - actionscript 3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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