我有JavaScript从表单中获取条目,然后在使用“GET”后搜索位置以将这些表单输入应用于值,因为您可以看到它最终与我使用for语句结合很长时间/ else if statement。提高效率的最佳方法是什么?
谢谢!
var search = location.search;
var parts = search.slice(1).split('&'); // Need to slice to remove initial '?'
for (var i=0; i < parts.length; ++i)
{
var info = parts[i].split('=');
var variable = info[0];
var value = info[1];
if(variable === "pNAME") {
var pNAME = value;
}
else if(variable === "mAB") {
var mAB = value;
}
else if(variable === "mPB") {
var mPB = value;
}
else if(variable === "mNA") {
var mNA = value;
}
else if(variable === "lPED") {
var lPED = value;
}
else if(variable === "lSS") {
var lSS = value;
}
else if(variable === "lSC") {
var lSC = value;
}
else if(variable === "lVIS") {
var lVIS = value;
}
else if(variable === "lPAR") {
var lPAR = value;
}
else if(variable === "lBUS") {
var lBUS = value;
}
else if(variable === "lTRAIN") {
var lTRAIN = value;
}
else if(variable === "cHT") {
var cHT = value;
}
else if(variable === "cRAM") {
var cRAM = value;
}
else if(variable === "cTMS") {
var cTMS = value;
}
else if(variable === "cCC") {
var cCC = value;
}
else if(variable === "cCG") {
var cCG = value;
}
else if(variable === "cSTRL") {
var cSTRL = value;
}
else if(variable === "cWEAL") {
var cWEAL = value;
}
else if(variable === "deWHI") {
var deWHI = value;
}
else if(variable === "deASI") {
var deASI = value;
}
else if(variable === "deBLA") {
var deBLA = value;
}
else if(variable === "deOTH") {
var deOTH = value;
}
else if(variable === "daYOU") {
var daYOU = value;
}
else if(variable === "daYM") {
var daYM = value;
}
else if(variable === "daM") {
var daM = value;
}
else if(variable === "daOL") {
var daOL = value;
}
else if(variable === "doPOP") {
var doPOP = value;
}
else if(variable === "doDENS") {
var doDENS = value;
}
else if(variable === "doSTU") {
var doSTU = value;
}
};
先谢谢你了!
答案 0 :(得分:3)
您可以使用变量创建一个对象,并将变量指定为属性 将name命名为属性名称。类似的东西:
var myVar = {};
for (var i=0; i < parts.length; ++i){
var info = parts[i].split('=');
myVar[info[0]] = info[1];
}
现在,您可以在一个对象中包含所有变量和值,例如myVar.lSS
或myVar.pNAME
。
答案 1 :(得分:0)
把你的pNAME,mAB ......也放在数组中,而不是这样做
function inArray(needle, haystack) {
var length = haystack.length;
for(var i = 0; i < length; i++) {
if(haystack[i] == needle) return true;
}
return false;
}