javascript - 本地存储正在将空对象添加到我的数组中

标签 javascript jquery local-storage

我使用本地存储创建了“添加到收藏夹”功能。当我从产品页面添加产品时,当我最初导航到我的收藏夹页面时,它们会被正确添加、存储和显示。但是,如果我在浏览器中来回导航或直接输入收藏夹页面 URL,则会收到此错误:

未捕获类型错误:无法读取 null 的属性“id”

出现错误的行是:id = item.id;

在处理错误时,我注意到一个空对象现在已添加到我的数组中。我不确定为什么要添加这个空对象。

以下是我添加的单个产品页面的代码:

var debug = true; // Set to true to output message to the error console
$(document).ready(function() {
  var favs = favInit();
  var item = {
    id:   '{{ dynamic_page_hubdb_row.hs_id }}',
    name: '{{ dynamic_page_hubdb_row.hs_name }}',
    url:  '{{ dynamic_page_hubdb_row.image.url }}',
    path: '{{ request.path }}'
  }
  var isFav = isFavorite(item,favs);
  if (isFav){
    setAsFavorite();
    $('#addFavorite').hide();
    $('#addFavoriteStar').hide();
    $('#removeFavorite').show();
    $('#removeFavoriteStar').show();
  } else {
    removeAsFavorite(item);
    $('#addFavorite').show();
    $('#addFavoriteStar').show();
    $('#removeFavorite').hide();
    $('#removeFavoriteStar').hide();
  }
  $('#addFavorite, #addFavoriteStar').click(function(e){
    e.preventDefault();
    if (debug) { console.log('adding item as a favorite'); }

    // Update localStorage
    setAsFavorite(item);

    // Update class
    $('#itm{{ dynamic_page_hubdb_row.hs_id }}').addClass('isFavorite');
      $('#addFavorite').hide();
    $('#addFavoriteStar').hide();
    $('#removeFavorite').show();
    $('#removeFavoriteStar').show();

    // Trigger modal
    $('#myModal').modal('show');

    return false;
  });
  $('#removeFavorite, #removeFavoriteStar').click(function(e){
    e.preventDefault();
    if (debug) { console.log('removing item from favorites'); }

    // Update localStorage
    removeAsFavorite(item);

    // Update class
    $('#itm{{ dynamic_page_hubdb_row.hs_id }}').removeClass('isFavorite');
    $('#addFavorite').show();
    $('#addFavoriteStar').show();
    $('#removeFavorite').hide();
    $('#removeFavoriteStar').hide();

    return false;
  });
});

function favInit(){
  // Get the existing favorites from localStorage
  var favs = JSON.parse(localStorage.getItem('favorites'));
  if (debug) { console.log('favInit-1 favorites: '+localStorage.getItem('favorites')); }
  // If localStorage.favorites doesn't exists, create an empty array
  if (favs != null && Array.isArray(favs) && favs.length){ } else {
    if (debug) { console.log('no favorites found in local storage. Creating an empty array'); }
    favs = new Array; // setup an empty array
    // Refresh local storage
    localStorage.setItem("favorites", JSON.stringify(favs));
    // pull favs from local storage
    favs = JSON.parse(localStorage.getItem('favorites'));
  }

  if (debug) { console.log('favInit-2 favorites: '); console.dir(favs); }

  return favs;
}

function isFavorite(item,favs){
  if (favs != null && favs.length){
    // Find the selected item in the favs array
    var test = favs.find(x => x.id === item.id);
    //var test = $.grep(favs, function(e){ return e.id == item.id; });
    if (test != null){
      if (debug) { console.log('item is already a favorite: '); console.dir(item); }
      return true;
    } else {
      if (debug) { console.log('item is not a favorite.'); }
      return false;
    }
  }
}

function setAsFavorite(item){
  var favs = JSON.parse(localStorage.getItem('favorites'));
  favs.push(item);
  localStorage.setItem('favorites',JSON.stringify(favs));
  if (debug) { console.log('favInit-1 favorites: '+localStorage.getItem('favorites')); console.dir(JSON.parse(localStorage.getItem('favorites'))) }
}

function removeAsFavorite(item){
  removeAsFavoriteByID(item.id)
}

function removeAsFavoriteByID(id){
  var favs = JSON.parse(localStorage.getItem('favorites'));
  var idx = favs.findIndex(x => x.id === id);
  delete favs[idx];
  var favs = favs.filter(function (el) {
    return el != null;
  });
  if (debug) { console.log('removeAsFavorite: '+favs); }
  if (favs.length){
    //console.log('favs does have a length');
    localStorage.setItem('favorites',JSON.stringify(favs));
  } else {
    //console.log('favs has no length');
    localStorage.setItem('favorites',JSON.stringify(new Array));
  }
  if (debug) { console.log('favInit-1 favorites: '+localStorage.getItem('favorites')); console.dir(JSON.parse(localStorage.getItem('favorites'))) }
}

if (debug){
  $('.product-ctas').append( '<a href="#" class="clearFavorites">clear favs</a>' );
  $('.product-ctas').on('click','.clearFavorites',function(e){
    e.preventDefault();
    localStorage.removeItem('favorites');
    alert('Favorites cleared');
    return false;
  });
}

这是我的收藏夹页面的代码:

var debug = true; // Set to true to output message to the error console
$(document).ready(function() {
  var favs = favInit();
  displayFavorites('#favorites-list',favs);
});

function favInit(){
  // Get the existing favorites from localStorage
  var favs = JSON.parse(localStorage.getItem('favorites'));
  if (debug) { console.log('favInit-1 favorites: '+localStorage.getItem('favorites')); }
  // If localStorage.favorites doesn't exists, create an empty array
  if (favs != null && Array.isArray(favs) && favs.length){ } else {
    if (debug) { console.log('no favorites found in local storage. Creating an empty array'); }
    favs = new Array; // setup an empty array
    // Refresh local storage
    localStorage.setItem("favorites", JSON.stringify(favs));
    // pull favs from local storage
    favs = JSON.parse(localStorage.getItem('favorites'));
  }

  if (debug) { console.log('favInit-2 favorites: '); console.dir(favs); }

  return favs;
}

function displayFavorites(containerID,array){
  var $list = $('<ul/>'), id, item, image, title;
  for (var i=0; i<array.length; i++){
    item = array[i];
    if (debug) { console.log('item '+i+': '); console.dir(item); }

    id = item.id;

    $image = $('<a/>').attr('href',item.path).append( $('<img/>').attr('src',item.url).attr('title',item.name) );
    $title = $('<strong/>').append( $('<a/>').attr('href',item.path).text(item.name) );
    $list.append( $('<li/>').attr('id','itm'+id).append($image).append($title) );
  }
  $(containerID).html($list);
}

function removeAsFavoriteByID(id){
  var favs = JSON.parse(localStorage.getItem('favorites'));
  var idx = favs.findIndex(x => x.id === id);
  delete favs[idx];
  var favs = favs.filter(function (el) {
    return el != null;
  });
  if (debug) { console.log('removeAsFavorite: '+favs); }
  if (favs.length){
    //console.log('favs does have a length');
    localStorage.setItem('favorites',JSON.stringify(favs));
  } else {
    //console.log('favs has no length');
    localStorage.setItem('favorites',JSON.stringify(new Array));
  }
  if (debug) { console.log('favInit-1 favorites: '+localStorage.getItem('favorites')); console.dir(JSON.parse(localStorage.getItem('favorites'))) }
}

最佳答案

不要使用delete,它将替换为null/undefined

var favs = [{}]

delete favs[0]

console.log(favs)

使用拼接

var favs = [{}]

favs.splice(0, 1)

console.log(favs)

关于javascript - 本地存储正在将空对象添加到我的数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56264048/

相关文章:

javascript - 如何使用 JavaScript 计算一行中的字符数

javascript - 在 AngularJS 中将值推送到本地存储不起作用

javascript - Vue.js axios 从本地存储(localforage)获取值返回promise对象而不是值

javascript - HTML Doctype 导致视频自动播放而不滚动到

Javascript: window.onload问题

javascript - JS try/catch 生成 jshint 错误

javascript - 使用javascript打开fancybox 2.1.4

javascript - jquery wrap, append, prepend 到父 div

javascript - 将文本定位在网格中的 x、y 位置

javascript - 如何用 jasmine 监视 localStorage 方法