清单1中有代码,清单2中有一个函数。两个片段都在同一个文件中,清单1中的片段一旦作用于清单2中的功能,它们就会很好地完成其他功能。如果将整个片段复制到一个函数中,那么一切都会起作用,但是您想使其变得更容易。如何在函数中调用部分代码?
列出1
var get_number = obj.Price.Itog;
var get_сurrency = obj.Currency.symbol;
function declOfNum(get_number, titles) {
return titles[(get_number%10==1 && get_number%100!=11) ? 0 : get_number%10>=2 && get_number%10<=4 && (get_number%100<10 || get_number%100>=20) ? 1 : 2]; //v3
}
if (get_сurrency == 'грн') {
var final_currency = declOfNum(get_number, ['грИвна', 'грИвны', 'грИвен']);
}
else if (get_сurrency == 'сом') {
var final_currency = declOfNum(get_number, ['сом', 'сома', 'сомов']);
}
else if (get_сurrency == 'тг') {
var final_currency = 'тенгЕ';
}
else {
var final_currency = declOfNum(get_number, ['рУбль', 'рублЯ', 'рублЕй']);
}
列出2
function GenTextPriceHour(obj)
{
var t = '';
var coeff;
if (obj.Tariff.tunes.C_PRICE_FACTOR == null) {
coeff = 1;
}else {coeff = obj.Tariff.tunes.C_PRICE_FACTOR;
}
if(obj)
{
if (obj.Price.Discount) {
t = t + getText(obj.Language.code,'PriceWithDiscountHour',[Round(obj.Price.Itog), final_currency]) + ' ';
} else {
t = t + getText(obj.Language.code,'PriceNoDiscountHour',[Round(obj.Price.Itog), final_currency]) + ' ';
}
}
return t;
}
答案 0 :(得分:0)
您正在尝试在final_currency
中使用GenTextPriceHour
。如果将if-else逻辑移至某个函数,则final_currency
函数将无法使用GenTextPriceHour
。
相反,请全局定义final_currency
,然后将更新代码移动到将更新全局变量的函数中,如下所示:
var get_number = obj.Price.Itog;
var get_сurrency = obj.Currency.symbol;
var final_currency = '';
function declOfNum(get_number, titles) {
return titles[(get_number%10==1 && get_number%100!=11) ? 0 : get_number%10>=2 && get_number%10<=4 && (get_number%100<10 || get_number%100>=20) ? 1 : 2]; //v3
}
function updateFinalCurrency() {
if (get_сurrency == 'грн') {
final_currency = declOfNum(get_number, ['грИвна', 'грИвны', 'грИвен']);
}
else if (get_сurrency == 'сом') {
final_currency = declOfNum(get_number, ['сом', 'сома', 'сомов']);
}
else if (get_сurrency == 'тг') {
final_currency = 'тенгЕ';
}
else {
final_currency = declOfNum(get_number, ['рУбль', 'рублЯ', 'рублЕй']);
}
}
答案 1 :(得分:0)
似乎您没有在任何地方调用GenTextPriceHour(obj)
函数。另外,您需要从if语句中将final_currency
定义为GLOBAL变量,以便它可以获取在if语句中传递给它的值,然后在{{1}中使用它}。目前,该变量是LOCALLY定义的,因此不能在function / if语句等外部使用。为此,在编号1中输入:
GenTextPriceHour(obj)