使用javascript检查变量中的值

时间:2015-06-21 03:52:47

标签: javascript

我想使用带if条件的JavaScript检查变量中的值。在这些情况下,变量location的值为var location="Banglore"。但每次去其他地方。

我的代码是

  var location="Banglore";
  if(typeof(location)== "Bangalore")
   {
      var data_file = "http://api.openweathermap.org/data/2.5/
      find?      q=Bangalore&units=metric";
   }
  else if(typeof(location) == "Chennai")
   {
      var data_file = "http://api.openweathermap.org/data/2.5/
      find?q=Chennai&units=metric";
   }
 else if(typeof(location) == "Cochi")
   {
      var data_file = "http://api.openweathermap.org/data/2.5/
      find?  q=Cochi&units=metric";
   }
 else 
   {
      var data_file = "http://api.openweathermap.org/data/2.5/
      find?q=Pune&units=metric";
   }

在这些代码中总是转到其他部分,即location == pune condition.Any body帮助我

4 个答案:

答案 0 :(得分:1)

问题是你有错误的检查值。

var location="Banglore";
  if(location == "Bangalore") // extra `a` after `g`
   {
      var data_file = "http://api.openweathermap.org/data/2.5/
      find?      q=Bangalore&units=metric";
   }
  else if(typeof(location) == "Chennai") // typeof gives here "string" as result
      //so your condition evaluates as
      // "string" == "Chennai", and so on for the rest,
      // hence it always goes to else block
   {
      var data_file = "http://api.openweathermap.org/data/2.5/
      find?q=Chennai&units=metric";
   }

也不要在本地块中声明变量,如果你要在给定的块之外使用它,这里是data_file在if..else块内声明。

答案 1 :(得分:1)

首先,你要比较错误的语法,

var location="Banglore";
  if(location == "Bangalore") // this should be location == "Banglore"
   {

第二件事是,

为什么使用typeof()检查其他城市?据我所知,你应该使用

var location="Banglore";
  if(location == "Banglore")
   {
      var data_file = "http://api.openweathermap.org/data/2.5/
      find?q=Bangalore&units=metric";
   }
  else if(location == "Chennai")
   {
      var data_file = "http://api.openweathermap.org/data/2.5/
      find?q=Chennai&units=metric";
   }
 else if(location == "Cochi")
   {
      var data_file = "http://api.openweathermap.org/data/2.5/
      find?q=Cochi&units=metric";
   }
 else 
   {
      var data_file = "http://api.openweathermap.org/data/2.5/
      find?q=Pune&units=metric";
   }

注意:您可能还必须删除查询中的空格。

答案 2 :(得分:1)

你应该使用switch语句,这就是它的意思......

var location = "Banglore",
    data_file = "http://api.openweathermap.org/data/2.5/find?units=metric&q=";

switch (location) {
    case "Bangalore":
        data_file += "Bangalore";
        break;
    case "Chennai":
        data_file += "Chennai";
        break;
    case "Cochi":
        data_file += "Cochi";
        break;
    default:
        data_file += "Pune";
}

答案 3 :(得分:0)

您正在将位置设置为' Banglore'和'如果'条件是'班加罗尔'。