Function keeps return NaN

时间:2018-09-18 20:18:58

标签: javascript nan

When the window loads, the console is returning indexIn.
But when I run the bottom function, it returns NaN.

const recentItem = document.querySelector('.recent-item');

var indexIn;

window.onload = function() {
  var indexIn = JSON.parse(localStorage.getItem("indexInStore"));
  var indexOut = JSON.parse(localStorage.getItem("indexOutStore"));
  var indexIn = Number(indexIn);
  console.log(indexIn);
}

var indexIn = indexIn;

recentItem.addEventListener('click', function() {
  console.log(indexIn);
});

1 个答案:

答案 0 :(得分:0)

Can you try:

const recentItem = document.querySelector('.recent-item');

var indexIn;

window.onload = function() {
  indexIn = Number(JSON.parse(localStorage.getItem("indexInStore")));
  var indexOut = JSON.parse(localStorage.getItem("indexOutStore"));
  console.log(indexIn);
}

recentItem.addEventListener('click', function() {
  console.log(indexIn);
});

You have indexIndefined globally then your are "redefining" it and setting in inside an "onload" function. Not good coding.