2015-09-07 106 views
1

在應用程序範圍中有一個LS對象,根據網頁部分包含產品或類別屬性。所以我必須檢查並保存localStorage中的數據。這是代碼:未定義對象的未定義屬性(在if else子句中)

if (LS.product !== 'undefined') { 

     data = { 
      'prod_id' : LS.product['id'], 
      'prod_name' : LS.product['name'], 
      'prod_price' : LS.variants[0]['price_number'], 
      'category' : '' //TODO 
     } 
     item_name = String('product-' + LS.product['id']) + '-' + String(Date.now()); 
     localStorage.setItem(item_name, JSON.stringify(data)); 
    } 
    else if (LS.category !== 'undefined') { 
     data = { 
      'category_id' : LS.category['id'], 
      'category_name' : LS.category['name'], 
     } 
     item_name = String('category-' + LS.category['id']) + '-' + String(Date.now()); 
     localStorage.setItem(item_name, JSON.stringify(data)); 
    } 
    else { 
     data = {}; 
    } 

的問題是,我得到的錯誤:

Uncaught TypeError: Cannot read property 'id' of undefined 

但如果我只執行代碼的相應部分工作正常。我一直在試圖找到一個解決方案,但沒有成功。

+7

字符串''undefined''只是一個字符串,而不是「未定義」的值。 – Pointy

+0

錯誤出現在'LS.product ['id']'還是'LS.category ['id']'? – LostMyGlasses

+0

if(typeof LS.category!=='undefined') –

回答

4

您應該檢查undefined作爲未定義的值,而不是作爲一個字符爲'undefined'

if (LS.product !== 'undefined') { 
... 
else if (LS.category !== 'undefined') { 

應該

if (LS.product !== undefined) { 
... 
else if (LS.category !== undefined) { 
2

您正在檢查字符串"undefined"而不是值undefined。嘗試if (LS.product !== undefined) {else if (LS.category !== undefined) {