我是javascript的新手,所以我的问题可能看起来很重要。如何使用for
循环使这段代码更简单,重复性更低:
SortingPageAudio.prototype.cardAudios = function (cardNumber) {
var page = tabs.page;
var card1Audio = page.card1Audio;
var card2Audio = page.card2Audio;
var card3Audio = page.card3Audio;
var card4Audio = page.card4Audio;
var card5Audio = page.card5Audio;
var card6Audio = page.card6Audio;
var FRcard1Audio = card1Audio.replace("e_", "f_");
var FRcard2Audio = card2Audio.replace("e_", "f_");
var FRcard3Audio = card3Audio.replace("e_", "f_");
var FRcard4Audio = card4Audio.replace("e_", "f_");
var FRcard5Audio = card5Audio.replace("e_", "f_");
var FRcard6Audio = card6Audio.replace("e_", "f_");
playAudio.stopAudioPlaying();
if (cardNumber == '0') {
(router.getLanguage() == 'french' ? playAudio.playFiles(FRcard5Audio) : playAudio.playFiles(card5Audio));
} else if (cardNumber == '1') {
(router.getLanguage() == 'french' ? playAudio.playFiles(FRcard4Audio) : playAudio.playFiles(card4Audio));
} else if (cardNumber == '2') {
(router.getLanguage() == 'french' ? playAudio.playFiles(FRcard3Audio) : playAudio.playFiles(card3Audio));
} else if (cardNumber == '3') {
(router.getLanguage() == 'french' ? playAudio.playFiles(FRcard2Audio) : playAudio.playFiles(card2Audio));
} else if (cardNumber == '4') {
(router.getLanguage() == 'french' ? playAudio.playFiles(FRcard1Audio) : playAudio.playFiles(card1Audio));
} else if (cardNumber == '5') {
(router.getLanguage() == 'french' ? playAudio.playFiles(FRcard6Audio) : playAudio.playFiles(card6Audio));
}
};
答案 0 :(得分:0)
我将如何做到这一点:
SortingPageAudio.prototype.cardAudios = function (cardNumber) {
var langs = {
french:{},
english:{}
};
var en = langs.english;
var fr = langs.french;
var audio;
for(var i = 1, max = 6; i <= max; i += 1){
audio = tabs.page['card' + i + 'Audio'];
en['audio' + i] = audio;
fr['audio' + i] = audio.replace('e_', 'f_');
}
playAudio.stopAudioPlaying();
playAudio.playFiles(langs[router.getLanguage()]['audio' + ((5 - cardNumber) || 6)];
};
但也许您应该将变量langs
(和所有内容)缓存出函数,因为它不会改变。
只需在你的函数中保留最后两行。
答案 1 :(得分:0)
不使用for
循环,您只需创建一个对象。
SortingPageAudio.prototype.cardAudios = function (cardNumber) {
var rel = {
'0': [tabs.page.card5Audio.replace("e_", "f_"), tabs.page.card5Audio],
'1': [tabs.page.card4Audio.replace("e_", "f_"), tabs.page.card4Audio],
'2': [tabs.page.card3Audio.replace("e_", "f_"), tabs.page.card3Audio],
'3': [tabs.page.card2Audio.replace("e_", "f_"), tabs.page.card2Audio],
'4': [tabs.page.card1Audio.replace("e_", "f_"), tabs.page.card1Audio],
'5': [tabs.page.card6Audio.replace("e_", "f_"), tabs.page.card6Audio]
};
playAudio.stopAudioPlaying();
router.getLanguage() == 'french' ? playAudio.playFiles(rel[cardNumber][0]) : playAudio.playFiles(rel[cardNumber][1]);
};