gpt4 book ai didi

Javascript - 替换大量 if 语句

转载 作者:行者123 更新时间:2023-11-28 11:26:18 25 4
gpt4 key购买 nike

我有几个不同的单选按钮,它们返回种族和性别。该脚本在内部应用程序内运行,因此我返回的是 7707330、7707333 和 7707336,而不是返回“男孩”、“女孩”或“两者”。与种族单选按钮类似。

然后,我需要根据种族和性别的组合验证数据。这是一个非常简单的任务,但我最终得到了 15 个 if 语句!一切都按其应有的方式工作,但必须有一个更清洁的解决方案吗?

function test(radioResults) {
var1 = radioResults[0].toString();
var2 = radioResults[1].toString();

var roll = parseFloat(parent.roll);

if (var2 == '7707330') {
gender = 'boy';
}
if (var2 == '7707333') {
gender = 'girl';
}
if (var2 == '7707336') {
gender = 'both';
}

if (var1 == '7707341') {
maori(gender);
}
if (var1 == '7707344') {
pasifika(gender);
}
if (var1 == '7707347') {
all(gender);
}
}

function maori(gender) {
//Maori
if (gender == 'boy') {
ethnicity = parseFloat(parent.getMBoys);
validation(ethnicity);
}
if (gender == 'girl') {
ethnicity = parseFloat(parent.getMGirls);
validation(ethnicity);
}
if (gender == 'both') {
ethnicity = parseFloat(parent.getTotalM);
validation(ethnicity);
}
}

function pasifika(gender) {
//Pasifika
if (gender == 'boy') {
ethnicity = parseFloat(parent.getPBoys);
validation(ethnicity);
}
if (gender == 'girl') {
ethnicity = parseFloat(parent.getPGirls);
validation(ethnicity);
}
if (gender == 'both') {
ethnicity = parseFloat(parent.getTotalP);
validation(ethnicity);
}
}

function all(gender) {
//All
if (gender == 'boy') {
ethnicity = parseFloat(parent.getBoys);
validation(ethnicity);
}
if (gender == 'girl') {
ethnicity = parseFloat(parent.getGirls);
validation(ethnicity);
}
if (gender == 'both') {
ethnicity = parseFloat(parent.getTotalRoll);
validation(ethnicity);
}
}

function validation(ethnicity) {

percent = ethnicity * 5 / 100;

if (ethnicity - percent > roll || (ethnicity + percent < roll)) {
parent.document.getElementById('CF_7784443').value = "FAIL";
} else {
parent.document.getElementById('CF_7784443').value = "PASS";
}
}

我该如何清理它?

最佳答案

我不确定这是否符合您的口味,但对我来说这似乎是一个更干净的解决方案。首先分别布置所有映射。然后将映射解析为 parent 的正确属性。然后为您检索到的属性调用验证一次。这是一个草图:

// map var1 and var2 to gender and ethnicity
var genderMap = { "7707330" : "boy", "7707333": "girl", "7707336": "both" };
var ethnicityMap = { "7707341": "maori", "7707344": "pasifica", "7707347": "all" };

// map gender and ethnicity to the correct property of "parent"
var props =
{ "boy":
{
"maori": "getMBoys", "pacifica": "getPBoys", "all": "getBoys"
},
"girl":
{
"maori": "getMGirls", "pacifica": "getPGirls", "all": "getGirls"
},
"all":
{
"maori": "getTotalM", "pacifica": "getTotalP", "all": "getTotalRoll"
}
};

// get the correct property
var prop = props[genderMap[var1]][ethnicityMap[var2]];

// run the validation
validation(parseFloat(parent[prop]));

关于Javascript - 替换大量 if 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10326898/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com