2015-04-21 35 views
0

我想拉對象的屬性並使該字符串成爲小寫字符串。由於某種原因,它不起作用:Javascript - 'toLowerCase()'無法在對象屬性上工作

我有一個對象,story,它有一個屬性status。狀態顯示爲「空置」或「佔用」或其他一些東西。我想編寫代碼,以便這張表的管理員可以寫入「空置」或「空置」,而不必擔心大寫。該狀態也顯示在頁面上,因此最好顯示「空置」的正確大小寫。但那不是重點。

我有一個if語句:

$.each(story, function(i){ 
    if(story[i].status == "vacant"){ 
     showVacant(i-1);  
    } else if(story[i].status == "occupied"){ 
     showOccupied(i-1); 
    } else if(story[i].status == "feature"){ 
     showFeatured(i-1); 
    } else { 
     showVacant(i-1); 
    } 
}); 

我試圖在if語句使用toLowerCase();

if(story[i].status.toLowerCase() == "vacant"){ 

但控制檯返回錯誤Cannot read property 'toLowerCase' of undefined。我也試圖使其與.toString()第一以及一個變量:

myStatus = story[i].status.toString(); 
if(myStatus.toLowerCase() == "vacant"){ 

但是,當涉及到這個聲明這給了我一個控制檯錯誤Cannot read property 'toString' of undefined

我怎樣才能確保字符串始終是小寫?

+2

您的狀態是不確定的,不確定有沒有的toString或toLowerCase方法。 –

回答

2

Cannot read property 'toLowerCase' of undefined意味着story[i].status沒有定義,所以它不是一個string,使toLowerCase()功能不可用它。

你需要檢查的故事[I] .STATUS「在使用它之前設置:

if (typpeof story[i].status != "undefined"){ 
    //do stuff with story[i].status 
} 
+0

這是讓我回答我的答案的解決方案。我簡化了if語句,只是說'if(story [i] .status){.../*執行語句* /}'。問題在於,第一個對象由於某種原因沒有狀態。無論如何,抓住它是件好事,而不是僅僅解決這個小問題。謝謝 – ntgCleaner

1

狀態設置不正確,而不是被「空置」或「被佔用」返回未定義。正因爲如此,你不能小寫或toString這個未定義的對象。

我會建議在代碼中的各個位置打印出對象的屬性,以確定它沒有正確設置或繼承此屬性的位置。

2

Cannot read property 'toLowerCase' of undefined表示story[i].status不存在。

而是執行此操作:

if("status" in story[i]) { 
    switch(story[i].status.toLowerCase()) { 
     case "vacant": 
      break; 
     case "occupied": 
      // etc 
    } 
}