for循环中的多个函数

时间:2012-12-03 03:22:19

标签: javascript jquery

我可以在for循环中创建多个函数吗?

var mySound1 = new buzz.sound( "laser-01", { formats: [ "ogg", "mp3", "acc" ]});
var mySound2 = new buzz.sound( "alien-noise-01", {formats: [ "ogg", "mp3", "acc" ]});

var sound = [mySound1, mySound2]

// additional sounds
var $i;
for ( $i = 0; $i< sound.length; $i++){
    function playsound[$i](){   
           a[$i].play().fadeIn().loop();
        }
}

playsound1();

2 个答案:

答案 0 :(得分:3)

您可以重复使用某个功能:

// declare your sound dictionary
var sounds = {
    'laser':       new buzz.sound( "laser-01", { formats: [ "ogg", "mp3", "acc" ]}),
    'alien-noise': new buzz.sound( "alien-noise-01", {formats: [ "ogg", "mp3", "acc" ]})
};

// this is the helper function
var playSoundFn = function() {
    this.play().fadeIn().loop();
};

// assign the helper function to all your sounds
for (var i=0, len=sounds.length; i<len; i++){
    sounds[i].playSound = playSoundFn;
}


// then play your sounds from any of them in your dictionary :
sounds['laser'].playSound();
sounds['alien-noise'].playSound(); 

** 修改 **(感谢TheSmose

如果sounds数组中的每个项目都是使用buzz.sound.prototype原型创建的,那么您只需添加一个自定义函数并只使用它:

// this is the helper function
buzz.sound.prototype.playSound = function() {
    this.play().fadeIn().loop();
};

// declare your sound dictionary
var sounds = {
    'laser':       new buzz.sound("laser-01", { formats: ["ogg", "mp3", "acc"]}),
    'alien-noise': new buzz.sound("alien-noise-01", {formats: ["ogg", "mp3", "acc"]})
};

// then play your sounds from any of them in your dictionary :
sounds['laser'].playSound();
sounds['alien-noise'].playSound(); 

答案 1 :(得分:1)

将$ i作为参数传递给playound函数

会更好
var sounds = [
    new buzz.sound( "laser-01", { formats: [ "ogg", "mp3", "acc" ]}),
    new buzz.sound( "alien-noise-01", {formats: [ "ogg", "mp3", "acc" ]})
];

var playsound = function (i) {   
   sounds[i].play().fadeIn().loop();
}

playsound(1);

如果你真的想要playsound1()样式函数名称,你可以评估它(虽然我建议不要添加它):

for (var i = 0; i < sounds.length; i++){
    eval('var playsound' + (i+1) + ' = function() { playsound(' + i + '); };');
}

playsound1();
playsound2();