2017-05-28 108 views
0

我有一个奇怪的JavaScript问题。我使用vue js和axios从API获取一些数据。我已经倾销console.log和值在那里,但我的if语句不会是真实的。Javascript如果不返回true

删除的东西,使代码示例更小。

请参阅行内评论。

HTML: 

<input v-model="system_id"> 
<button v-on:click="getSystemData" class="btn btn-primary">Get system data</button> 


Data model: 

data:() => ({ 
    errors: [], 
    system_id: null, 
    system_data: null 
}), 



Function: 

getSystemData() { 
    HTTP.get('/api/get_systems') 
    .then(response => { 
     this.response = response.data 

     // equals 1234 
     console.log(this.system_id) 
     for (var key in this.response) { 

     // the id 1234 is found here in a large list 
     console.log(this.response[key].system_id) 


     // Does not go true?!?! 
     if (this.response[key].system_id === this.system_id) { 
      this.system_data = this.response[key].system_data 
     } 
     } 
    }) 
    .catch(e => { 
     this.errors.push(e) 
    }) 
    } 

为什么if从不触发?

+0

首先我要确保该声明实际上是真实的。比如先把一个调试器放在一行中。或者,如果声明是真实的,你是如何证明自己的? – trueunlessfalse

+0

'this.system_id'的类型是什么? https://stackoverflow.com/questions/359494/which-equals-operator-vs-should-be-used-in-javascript-comparisons –

+0

尝试使用'=='而不是'==='。 '==='运算符检查值和类型。我不知道你的情况,但也许你的价值观有不同的类型,例如数字和字符串? – mingos

回答

2

这个问题可能与不匹配的数据类型有关。 ===运算符将为if(1234 ===“1234”)返回false。使用==运算符

+2

为了理解错误,我仍然建议使用调试器,看看类型是如何不同,并试图理解为什么。然后你可以有意识地决定在这里使用==,而在其他情况下这可能是一个不好的选择。 – trueunlessfalse

+0

是的,它是字符串与整数比较。我不得不使用:if(this.response [key] .system_id === Number(this.system_id))...使用== eslint抱怨。 – John