【问题标题】:How can i fix this undefined output text in javascript function [duplicate]如何在javascript函数中修复这个未定义的输出文本[重复]
【发布时间】:2021-07-10 11:44:15
【问题描述】:

我使用 javascript 制作了一个简单的计算器。我在下面提供这些代码。但问题是当我运行这些代码时。我看到了一个未定义的输出。我不知道为什么显示该文本。我想删除它。

function addition(x, y) {
  var sum = x + y;
  document.write("Addition of two number is : " + sum);
}

function substract(x, y) {
  var sub = x - y;
  document.write("Subtraction of two number is : " + sub);
}

function multiply(x, y) {
  var multiply = x * y;
  document.write("Multipication of two number is : " + multiply);
}

function division(x, y) {
  var division = x / y;
  document.write("Division of two number is : " + division);
}

var x = parseInt(prompt("Enter the first number : "));
var y = parseInt(prompt("Enter the second number : "));

var operator = prompt("Enter the operator : ");

if (operator == "+") {
  document.write(addition(x, y));
} else if (operator == "-") {
  document.write(substract(x, y));
} else if (operator == "*") {
  document.write(multiply(x, y));
} else if (operator == "/") {
  document.write(division(x, y));
} else {
  document.write("Invalid Operator. Please choose operator between +,-,* or /. <br> Thanks for using our calculator. ");
}

【问题讨论】:

  • @Andy 仅仅因为问题具有相同的关键字“为什么”和“未定义”并不能使其成为一个常见问题。建议的已回答问题在这里没有帮助。
  • @vanowm,但这个问题很久以前就解决了。如果函数不返回任何其他内容,则函数返回 undefined

标签: javascript


【解决方案1】:

调用document.write(x) 会导致写入x。如果x 是一个函数调用,它将写入该函数调用返回的任何内容。由于您的所有函数都没有显式返回某些内容,因此它们返回(来了)undefined

【讨论】:

    【解决方案2】:

    您的运算符函数不返回任何内容,它们直接写入页面。 然而,执行这些函数的行会将这些函数的返回值写入页面,即undefined

    所以要解决这个问题,你有两个选择:

    1. 在运算符函数中将document.write("blah") 替换为return "blah"
    2. 从调用者中删除document.write()document.write(addition(x, y))

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-07
      • 1970-01-01
      • 1970-01-01
      • 2016-09-28
      • 2021-05-11
      • 2018-03-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多