如何通过本地存储过滤循环

How to filter a loop through local storage

我正在尝试将 link 添加到我的导航栏以显示用户进行的搜索,以及用户是否收藏了 link。我目前想要实现的是,如果“过去搜索”部分已经包含当前搜索,请不要添加当前搜索以避免重复。我正在使用 localStorage 将此数据与字符串化数组 (alreadySearched) 一起存储,并检查此数组是否包含当前搜索;我的问题 是函数总是 returns false。 收藏夹下拉列表也会发生同样的事情。我做错了什么?

这是我的代码:

// primary movie information (API #1)
var getMovie = function(title) {
  $("#result").addClass("hidden")
  $("#main").removeClass("hidden");
  $("#search-form").trigger("reset");
  //format the OMDB api url 
  var apiUrl = `http://www.omdbapi.com/?t=${title}&plot=full&apikey=836f8b0`
  //make a request to the url 
  fetch(apiUrl)
    .then(function(response) {
      // request was successful 
      if (response.ok) {
        response.json().then(function(movieData) {
          // console.log(movieData)
          var movieTitle = movieData.Title
          getMovieId(movieTitle);
          getSoundTrack(movieTitle);
          getTrailer(movieTitle);
          var movieObj = {
            title: movieTitle,
          }
          var pastSearches = loadPastSearches();
          var alreadySearched = false
          if (pastSearches) {
            pastSearches.forEach(s => {
              if (s.title === movieTitle) {
                alreadySearched = true;
              }
            })
          }
          if (!alreadySearched) {
            for (var item of pastSearches) {
              let searchEl = document.createElement("a")
              let pastSearchTitle = item.title
              $(searchEl).text(pastSearchTitle)
              $(searchEl).addClass("past-search-item");
              $("#past-search-dropdown").append(searchEl)
              $(searchEl).click(function(e) {
                e.preventDefault();
                let title = pastSearchTitle
                getMovie(title)
                getQuotes(title)
              });
            }
          }
          saveSearch(movieObj)
          showMovie(movieData);
        });
      } else {
        alert("Error: title not found!");
      }
    })
    .catch(function(error) {
      alert("Unable to connect to CineXScore app");
      console.log(error)
    });
};


// save past search
var saveSearch = function(movieObj) {
  var pastSearches = loadPastSearches();
  pastSearches.push(movieObj);
  localStorage.setItem("movieObjects", JSON.stringify(pastSearches))
}
loadPastSearches = function() {
  var pastSearches = JSON.parse(localStorage.getItem("movieObjects"));
  if (!pastSearches || !Array.isArray(pastSearches)) {
    var pastSearches = []
  }
  return pastSearches;
}
// dropdown favorite soundtrack buttons 
var saveTrack = function(trackObj) {
  var faveTracks = JSON.parse(localStorage.getItem("trackObjects"));
  if (!faveTracks || !Array.isArray(faveTracks)) {
    var faveTracks = []
  }
  var alreadySearched = false
  if (faveTracks) {
    faveTracks.forEach(t => {
      if (t.name === trackObj.name) {
        alreadySearched = true;
      }
    })
  }
  if (!alreadySearched) {
    let trackEl = document.createElement("a")
    $(trackEl).addClass("fave-track");
    $(trackEl).text(trackObj.name);
    $(trackEl).attr("href", trackObj.url);
    $(trackEl).attr("target", "_blank")
    $("#favorite-tracks-dropdown").append(trackEl)
  }
  faveTracks.push(trackObj);
  localStorage.setItem("trackObjects", JSON.stringify(faveTracks))
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- Navigation Menu -->
<nav class="navbar navbar-default navbar-fixed-top">
  <a id="logo" class="navbar-brand">CineXScore</a>
  <div class="dropdown navbar-brand">Past Searches
    <i class="fa fa-caret-down"></i>
    <div id="past-search-dropdown" class="dropdown-content">
      <a id="clear-searches">Clear</a>
    </div>
  </div>
  <div class="dropdown navbar-brand">Favorite Tracks
    <i class="fa fa-caret-down"></i>
    <div id="favorite-tracks-dropdown" class="dropdown-content">
      <a id="clear-favorites">Clear</a>
    </div>
  </div>
</nav>

我认为这是一个简单的实现,可能会对您有所帮助。

async function fetchMovie(movieTitle) {
  const apiUrl = `http://www.omdbapi.com/?t=${movieTitle}&plot=full&apikey=836f8b0`;

  let res = await fetch(apiUrl);
  res = await res.json();

  const title = res.Title;
  saveSearch(title); //   Should only pass the string:title
}

fetchMovie('spiderman');

function saveSearch(title) {
  if (!localStorage.getItem('movies')) localStorage.setItem('movies', ''); //   Initialize the localStorage

  //   e.g: (In localStorage)
  //   Avenger,Spiderman,The Antman etc..
  //   return this string & convert into an array

  let movies = localStorage
    .getItem('movies')
    .split(',')
    .filter((n) => n);

  //   Check if the title is already exists
  if (!movies.includes(title)) {
    movies.push(title);
  }

  //   Also store in localStorage as a string seperated by commas (,)
  movies = movies.join(',');

  localStorage.setItem('movies', movies);
}