首页 > 解决方案 > 为什么 JS 在 HTML 中显示“未定义”

问题描述

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html><head></head><body>

<script type="text/javascript" src="/d2l/common/math/MathML.js?v=20.21.3.28143 "></script><script 
type="text/javascript">document.addEventListener('DOMContentLoaded', function() { 
D2LMathML.DesktopInit('https://s.brightspace.com/lib/mathjax/2.7.4/MathJax.js? 
config=MML_HTMLorMML','https://s.brightspace.com/lib/mathjax/2.7.4/MathJax.js?config=TeX-AMS- 
MML_HTMLorMML','130'); });

var add;
var cube;
var total;
var a;
var b;
function x(a, b) {
  var add = a + b;
    return add;
}

function y() {
    var cube = add * 3;
    return cube;
}

var total = x(7, 7);

if (a != b) {
    document.write(add);
}
else {
    document.write(cube);
    }

</script></body></html>

https://jsfiddle.net/161020/vu82kc3o/2/

我在介绍 Web 编程,我们应该编写一个程序,将两个数字相加并显示总数,但如果数字相同,那么它将它们加在一起并将总和乘以 3,然后再显示总数。我得到了第一部分,但是当我尝试为第二部分添加代码时,它只是在 html 中显示“未定义”。我使用的验证器说“'document'在定义之前使用过。document.write(add);”。我们应该在我们的代码中使用 document.write,并且 html 是在我们给定的模板中提供的。谁能指出问题所在的方向?

标签: javascriptfunction

解决方案


欢迎使用 JavaScript!我认为您正在过度设计解决方案。首先,让我们确定您要编写的函数。从你的问题

编写一个程序,将两个数字相加并显示总数,但如果数字相同,则将它们相加并在显示总数之前将总和乘以 3。

在我们担心显示数字之前,让我们得到答案。我们需要一个带有 2 个参数的函数来执行所需的操作:

function customOperation(a, b) {
  if (a === b) {
    return (a + b) * 3; // if the two numbers are the same, sum and multiply by 3
  } else {
    return (a + b); // otherwise, just sum the numbers
  }
}

现在我们有了一个函数,我们可以调用它,并将响应写入文档:

function customOperation(a, b) {
  if (a === b) {
    return (a + b) * 3; // if the two numbers are the same, sum and multiply by 3
  } else {
    return (a + b); // otherwise, just sum the numbers
  }
}

document.write(customOperation(3, 3)); // 18
document.write('<br>'); // line break
document.write(customOperation(4, 5)); // 9


推荐阅读