函数保持返回NaN

问题描述 投票:-2回答:1

窗口加载时,控制台返回索引In。 但是当我运行底部函数时,它返回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);
});
javascript nan
1个回答
0
投票

你能试一下吗:

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);
});

你有全局indexIndefined然后你正在“重新定义”它并设置在“onload”函数内。编码不好。

© www.soinside.com 2019 - 2024. All rights reserved.