JavaScript IF 语句运算符不匹配 (x == 1 && y == 'Parameter')

JavaScript IF statement Operators not matching (x == 1 && y == 'Parameter')

几天来我一直在努力解决这个问题,目前可能对这个问题视而不见。

我正在设置参数并将它们传递给一个函数,我想通过在一系列 IF/Else IF 语句中匹配参数来进行下一步。这是一个例子:

function Test(type, time) {
  this.state = {
    type: 1,
    time: '1H'
  }
  this.render()
}

Test.prototype.setState = function(newState) {
  for (var key in newState) {
    this.state[key] = newState[key]
  }
  var timeee = JSON.stringify(this.state.type);
  var typeee = JSON.stringify(this.state.time);

  document.getElementById('test1').innerHTML = timeee;
  document.getElementById('test2').innerHTML = typeee;

  this.render()
}

Test.prototype.render = function() {
  var type = this.state.type;
  var time = JSON.stringify(this.state.time);

  testDay(type, time);
}

function testDay(type, time) {
  console.log(">>>>> TYPE IS: " + type + " " + "TIME IS: " + time + " <<<<<")
  if(type == 1 && time == '1H'){
     console.log("-1-24-");
     } 
  else if(type == 2){
       console.log("-2-");
     }
  else {
    console.log("NO MATCH");
  }
};

var myTest = new Test()

不知何故,当我添加 'time' 的第二个参数时,它破坏了整个过程。如果您对此有任何想法或经验,我将非常感激,因为我有点生气。我的最终目标是这样的:

  if(type == 1 && time == '1M'){ 
     //call specific function
     } 
  else if(type == 1 && time == '1H'){ 
     //call specific function
     }
  else if(type == 1 && time == '1D'){ 
     //call specific function
     }
  else if(type == 2 && time == '1M'){ 
     //call specific function
     }
  else if(type == 2 && time == '1H'){ 
     //call specific function
     }
  else if(type == 2 && time == '1D'){ 
     //call specific function
     }
  else {
    console.log("NO MATCH");
  }

这是一个您可以修改的示例:

http://jsbin.com/semevi/3/edit?html,js,output

     if(type == 1 && time == '"1M"'){ //use this to override
 console.log("1, 1M"); 
 } 
     else if(type == 2){ //matching just the first parameter works
   console.log("1, 1H"); 
 }
     else {
console.log("NO MATCH");

}

已修复..引号问题

从调试来看,您的 time 变量似乎有一组额外的引号,因此它不会匹配 '1M'。只需删除那组额外的引号。还使用调试器来追踪这些问题

变化:

var time = JSON.stringify(this.state.time);

至:

var time = this.state.time;

此外,我建议您将那组 if 语句更改为嵌套语句,以提高可读性和整体更好的编码风格:

if (type === 1) {
    if (time === '1M') {
        //call specific function
    } else if (time === '1H') {
        //call specific function
    } else if (time === '1D') {
        //call specific function
    } else {
        console.log("NO MATCH");
    }
} else if (type === 2) {
    if (time === '1M') {
        //call specific function
    } else if (time === '1H') {
        //call specific function
    } else if (time === '1D') {
        //call specific function
    } else {
        console.log("NO MATCH");
    }
}

另请注意使用 === 而不是 == 以获得更快更严格的匹配。