javascript - 将函数调用传递给 $(document).ready 会导致变量为 NaN

标签 javascript nan var

为什么此代码将 spentScores 返回为 NaN?

$(document).ready(initScores());

var lvlScores = 0;
var currentScores = 0;
var spentScores = 0;

function initScores() {
  console.log(spentScores);
  console.log(spentScores + 44);
  console.log(lvlScores);
  initLvlScores();
  initSpentScores();
  initCurrentScores();
}

function recountLvlScores() {
  initScores();
  clearStatistics();
}

function initLvlScores() {
  var lvl = parseInt($('.lvl-select').val());
  switch (lvl) {
    case 1:
      lvlScores = 1000;
      break;
    case 2:
      lvlScores = 1200;
      break;
    case 3:
      lvlScores = 1500;
      break;
    case 4:
      lvlScores = 2000;
      break;
    case 5:
      lvlScores = 3000;
      break;
  }
}

function initSpentScores() {
  $('.statistics').each(function() {
    console.log("!!" + spentScores + parseInt($(this).val()));
    console.log("!!" + parseInt($(this).val()));
    spentScores = spentScores + parseInt($(this).val());
  });
}

function initCurrentScores() {
  currentScores = lvlScores - spentScores;
  $('.scores').html(currentScores);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>

控制台:

scoresEditCounting.js:9 undefined
scoresEditCounting.js:10 NaN
scoresEditCounting.js:11 undefined
scoresEditCounting.js:40 !!undefined44
scoresEditCounting.js:41 !!44
scoresEditCounting.js:40 !!NaN44
scoresEditCounting.js:41 !!44

最佳答案

更新这一行:

$(document).ready(initScores());

对此:

$(document).ready(initScores);

您希望页面在准备就绪时调用该函数。否则,您将在页面准备好之前尝试访问 DOM 元素。

关于javascript - 将函数调用传递给 $(document).ready 会导致变量为 NaN,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43077797/

相关文章:

javascript - 一个变量可以使用两次吗?

c++ - 如何不出错地除以零

r - 删除具有nan值的行

c# - 将数据从 var 类型转换为 Version 类型

javascript - SlickGrid 中可以使用可变行高吗?

javascript - 需要在 bootstrap.js 之后加载 bootstrap-dropdown.js 才能使下拉列表工作 - 为什么?

javascript - 在鼠标悬停和离开时动画 div

javascript - Three.js 如何确保模型加载后加载其他 javascript 文件

java - while 循环不正确地解析 Double.IsNaN

javascript - 如何将用户输入存储为 JavaScript 变量以供以后使用