如何在javascript中存储值并在需要时进行比较

时间:2013-01-15 13:47:40

标签: javascript html hashmap

我有以下值需要硬编码并在javascript中进行比较

值为:

SR = PlantWRShippingMail@shawinc.com
26 = Plant26ShippingMail@shawinc.com
29 = Plant29ShippingMail@shawinc.com
30 = Plant30ShippingMail@shawinc.com
34 = Plant34ShippingMail@shawinc.com
54 = Plant54ShippingMail@shawinc.com
41 = Plant41ShippingMail@shawinc.com
47 = Plant47ShippingMail@shawinc.com
DL = Plant.DL.Shipping.Mail@shawinc.com
37 = Plant37ShippingMail@shawinc.com
MU = PlantMUShippingMail@shawinc.com
UC = PlantUCShippingMail@shawinc.com
NB = plantnbshippingmail@shawinc.com

等等

我必须将值与现有值比较,如

var plantNo=document.getElementById('plantNo').value;
if(plantNo=`anyonevaluefromAbove`){
    //than get the value of it.
}

如何在javascript中执行此操作。

3 个答案:

答案 0 :(得分:2)

您可以简单地使用JS Object

var obj = {
SR: "PlantWRShippingMail@shawinc.com", ...
}

然后简单地看

if(obj[plantNo]) {
// obj[plantNo] is value 
}

这就是你想要的吗?

答案 1 :(得分:2)

您需要使用对象将硬编码值存储为地图;首先将所有植物存放在一个物体中:

var plants = {
  SR: "PlantWRShippingMail@shawinc.com",
  26: "Plant26ShippingMail@shawinc.com",
  29: "Plant29ShippingMail@shawinc.com",
  // and so on
  NB: "plantnbshippingmail@shawinc.com"
};

然后使用以下方法从对象中查找值:

var plantNo=document.getElementById('plantNo').value;
if(plants[plantNo]){
  alert(plants[plantNo]);
}

答案 2 :(得分:0)

您可以将这些值存储在javascript对象中。

var someobj = {'SR' : 'PlantWRShippingMail@shawinc.com'
               // other keys
};

var plantNo=document.getElementById('plantNo').value;
if(someobj[plantNo]){
    alert(someobj[plantNo]); // than get the value of it.
}