if else子句中未定义对象的未定义属性

时间:2015-09-07 15:48:38

标签: javascript

应用范围中有一个LS对象,具体取决于网页部分,包含产品或类别属性。所以我必须检查并保存localStorage中的数据。这是代码:

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

但如果我只执行代码的相应部分,则可以正常工作。我一直试图找到一个解决方案,但没有成功。

2 个答案:

答案 0 :(得分:4)

您应该将<style name="AppTheme" parent="@style/Theme.AppCompat.Light.DarkActionBar"> 检查为未定义的值,而不是undefined

的字符串
'undefined'

应该是

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

答案 1 :(得分:2)

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

相关问题