Actionscript 3 如何从数组中获取函数参数?
我在编码方面不是很先进,但我想做如下工作:Actionscript 3 如何从数组中获取函数参数?,actionscript-3,actionscript,Actionscript 3,Actionscript,我在编码方面不是很先进,但我想做如下工作: function something(id){ somethingElse(id); anotherThing(id); } var sampleArray:Array = [1,2,3]; something(1); something(2); something(3); 但是,无论数组有多长,我希望它都能将函数与数组中每个项的参数保持一次 有什么帮助吗 试试以下方法: function something(id):void{
function something(id){
somethingElse(id);
anotherThing(id);
}
var sampleArray:Array = [1,2,3];
something(1);
something(2);
something(3);
但是,无论数组有多长,我希望它都能将函数与数组中每个项的参数保持一次
有什么帮助吗 试试以下方法:
function something(id):void{
somethingElse(id);
anotherThing(id);
}
var sampleArray:Array = [1,2,3];
something(sampleArray[0]);
something(sampleArray[1]);
something(sampleArray[2]);
以下是如何将
函数something(数组\u元素)
应用于任意长度数组:
sampleArray.forEach(something);
但是,它不允许您在数组中改变元素(除非它们本身包含对其他项的引用,并且您正在更改)
参考:
示例:
我已经有一段时间没有做AS3了
以下内容应位于AS3类定义中,并提供一个公共函数,该函数接受uint和
累计两个以上的UINT:
private var _greater_than_two:Vector<uint>;
private function _append_greater_than_two(item:uint):void {
if (item > 2) {
_greater_than_two.push(item);
}
}
// Ok, We're assuming that the array is strictly typed and full of uints.
public function collect_greater_than_twos(items:Vector<uint>) {
// Append to the class instance _greater_than_two Vector any uint that is greater than two:
items.forEach(_append_greater_than_two);
// Tell us what is inside _greater_than_two now:
trace("The _greater_than_two Vector has " + contents.join(', '));
}
private var\u大于\u二:向量;
私有函数_追加_大于_二(项:uint):无效{
如果(项目>2){
_大于两个。推动(项目);
}
}
//好的,我们假设数组是严格类型的,并且充满了uint。
公共函数集合大于两个(项:向量){
//将大于2的任何uint追加到类实例_大于_than_two向量:
项目。forEach(\u追加\u大于\u两个);
//告诉我们里面有什么比两个大:
trace(“大于两个向量有”+内容。join(',');
}
另一个用例可能是有条件地添加到数据库中。让我们假设我们正在构建一个MMORPG,您想要跟踪玩家说“Hodor”的次数
下面再次假设这是在一个类中(我们称之为Player):
private\u redis:redis//假设您在构造函数中填充了此值
private\u playerName:String;
私有函数_detect_hodors(操作:字符串):void{
if(action.indexOf('Hodor')>-1){
_redis.incr(_playerName+‘actions’,1);
}
}
公共功能流程\用户\操作(操作:向量):无效{
行动。forEach(\u detect\u hodors);
//在这里做其他事情。。。
}
很多公司都希望您用一个简单的for循环来表达上述内容(假设我们使用的是上面的_append _greater _than _twos函数):
函数collect\u大于\u两个(项:数组):void{
var指数:uint;
var项:uint;
变量结束:uint=items.length;
对于(索引=0;索引
当我在做AS3时,我们避免使用foreach构造,因为它们比使用bare for循环和索引访问慢得多。不过,从那以后情况可能会发生变化。您能提供一个使用示例吗?我对这些东西不太在行,当然。回想一下,函数的名称类似于变量。我上面的例子假设您使用的是一个向量,但它很容易将端口转移到数组(实际上只是向量)。最终,您可以使用Array.forEach或只编写for循环(如示例所示)
private _redis:Redis; //assuming you filled this value in the constructor
private _playerName:String;
private function _detect_hodors(action:String):void {
if (action.indexOf('Hodor') > -1) {
_redis.incr(_playerName + 'actions', 1);
}
}
public function process_user_actions(actions:Vector<String>):void {
actions.forEach(_detect_hodors);
// Do other things here...
}
function collect_greater_than_twos(items:Array):void {
var index:uint;
var item:uint;
var end:uint = items.length;
for (index=0; index < end; index++) {
item = items[index] as uint;
_append_greater_than_twos(item);
}
}