2017-05-28 107 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