【发布时间】:2020-11-07 10:05:07
【问题描述】:
尝试为自己构建一个计算器,它需要两个提示数字,然后有一组单独的按钮来评估它们
我遇到的问题如下,我将提示的 number1 和 number2 保存为变量,但是当我尝试在外部函数中调用变量时,它告诉我变量(number1 和 number2)是未定义
有什么帮助吗?
ps:我已经开始做加法按钮了,接下来会加sub/mult/div,只需要开始第一个就行了
// the user is required to choose two sets of numbers that are then stored as variables
function numRequest() {
var number1 = prompt('choose the first number to evaluate:');
var number2 = prompt('choose the second number to evaluate:');
// just an external checker to see if the prompt is being saved
console.log('first choice --> ' + number1);
console.log('second choice --> ' + number2);
// the numbers, stored as variables, are displayed on the calculator window
document.getElementById('resBanner').innerHTML = ('you chose ' + number1 + ' and ' + number2);
}
// this is where the problem arises
// when i press the button that summons the function addition(), the two numbers arent
// defined for some reason
function addition() {
var res = Number(number1) + Number(number2);
document.getElementById('resBanner').innerHTML = res;
}
// function subtraction() {}
// function division() {}
// function multiplication() {}
【问题讨论】:
-
变量被声明为
numRequest函数的本地变量。您需要将它们设为全局变量,以便两个函数都可以访问它们。 -
虽然这本身就是一个副本,但您只需在此处少滚动即可。
-
@Barmar 欢呼,那么这也适用于新功能吗?新函数可以使用全局变量中的相同值吗?
-
所有函数都可以访问全局变量。 @DrFaraday
标签: javascript html dom-events calculator