【问题标题】:how to store values in javascript and compare them when needed [closed]如何在javascript中存储值并在需要时进行比较[关闭]
【发布时间】:2012-12-29 15:16:05
【问题描述】:

我有以下值需要在 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 中执行此操作。

【问题讨论】:

  • JS 中的对象可以完成这项工作。例如o['key'] = 'value'
  • 你试过什么?这就像在关联数组中查找值一样简单。
  • 不知道谁建议关闭,但我可以知道这样做的原因,这样我们以后就可以避免问这样的问题了。
  • 您显然没有在研究上投入太多精力。

标签: javascript html hashmap


【解决方案1】:

你可以简单地使用 JS 对象

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

然后只是看

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

这是你想要的吗?

【讨论】:

    【解决方案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]);
    }
    

    【讨论】:

      【解决方案3】:

      您可以将这些值存储在 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.
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-11-20
        • 1970-01-01
        • 2011-01-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多