加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

数组 – as3随机数组 – 随机化数组 – actionscript 3

发布时间:2020-12-15 07:32:20 所属栏目:百科 来源:网络整理
导读:你如何使用actionscript 3随机化一个数组? 解决方法 有一个使用Array.sort()函数的简短版本: 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 )
你如何使用actionscript 3随机化一个数组?

解决方法

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

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

如果你没有“足够”随机性,你可以排序两次:)

编辑 – 逐行说明:

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

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

  • A negative return value specifies that A appears before B in the sorted sequence.
  • A return value of 0 specifies that A and B have the same sort order.
  • A positive return value specifies that A appears after B in the sorted sequence.

注意:比较函数参数可能是键入的(如果您的数组是键入的)并且具有您想要的任何名称,例如:

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

当您需要按特殊属性对数组元素进行排序时,此方法非常有用.在随机化的情况下,compareFunction随机返回-1,0或1,并使数组元素切换它们的位置(索引).我发现更好的随机化(在我的主观和数学上未经测试的意见)是当方法仅返回-1和1.还要记住,使用自定义比较函数doesn’t compare elements sequentially排序函数,因此在某些特殊情况下,随机化结果可能与您的不同期望.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读