[英]Javascript. How can I access a variable outside of a function?
我正在尝试创建一个简单的应用程序,该应用程序使用 onclick 生成随机问题,并将使用不同的 onclick 生成所述问题的解决方案。 我已经能够简单地创建随机问题 function,但我遇到的问题是解决方案部分。 基本上我无法访问从“生成问题”function 产生的变量。
以下 function 生成一个随机问题:“Convert 10mg/mL to mcg/mL”
const arr = ['mg/mL', 'mcg/mL', 'mg/L'];
function genConversion () {
function clearBox(elementID){ //this resets the question
document.getElementById(elementID).innerHTML = "";
}
clearBox('output');
function shuffle(a) {
for (let i = a.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[a[i], a[j]] = [a[j], a[i]];
}
return a;
}
function randomNum() {
var number = Math.floor((Math.random() * 100) +1);
return number
}
var num = randomNum()
shuffle(arr);
output.innerHTML += "Convert " + num + ' ' + arr[0] + ' to ' + arr[1]
}
现在,当我尝试创建一个 function 来解决生成的问题时(一旦我弄清楚如何访问问题变量,实际逻辑就会出现),我似乎无法访问变量“num”。 有趣的是,我能够访问随机数组元素 arr[0]。
function solveProb() {
console.log(arr[0]);
console.log(num);
}
我确定这与我遇到问题的 scope 有关,但任何建议都将不胜感激。
只需在外部声明num
变量,然后在genConversion
内部分配给它,就像在外部声明arr
变量一样:
const arr = ['mg/mL', 'mcg/mL', 'mg/L']; let num; function genConversion () { function clearBox(elementID){ //this resets the question document.getElementById(elementID).innerHTML = ""; } clearBox('output'); function shuffle(a) { for (let i = a.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); [a[i], a[j]] = [a[j], a[i]]; } return a; } function randomNum() { var number = Math.floor((Math.random() * 100) +1); return number } num = randomNum() shuffle(arr); output.innerHTML += "Convert " + num + ' ' + arr[0] + ' to ' + arr[1] } genConversion(); document.querySelector('button').addEventListener('click', () => { console.log('Random generation was: ', "Convert " + num + ' ' + arr[0] + ' to ' + arr[1]); });
<div id="output"></div> <button>click</button>
如您所见, arr
是一个全局变量(未在任何函数内声明),但 num 在genConversion
内声明,因此它只存在于那里。
只需将 function 上方的变量定义为“let”,然后在 function 中修改变量。 然后调用 function。 然后您可以访问 function 外部变量的更新值。
let a = null;
const func = () => a = 5;
func();
console.log(a); // 5
您实际上并不想访问 function 之外的变量。 您已经在考虑函数,因此您可能会从我的库rubico中受益。 这是功能性、单向数据流样式的代码。 此外,使用let
和const
代替var
以避免不可预测的范围相关行为。
import { pipe, fork } from 'https://deno.land/x/rubico/rubico.js'
// if you're in the browser, use script type='module' for the import to work
const clearBox = elementID => {
document.getElementById(elementID).innerHTML = "";
}
const shuffle = a => {
for (let i = a.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[a[i], a[j]] = [a[j], a[i]];
}
return a;
}
const randomNum = () => {
const number = Math.floor((Math.random() * 100) +1);
return number
}
const arr = ['mg/mL', 'mcg/mL', 'mg/L']
const randomUnits = () => {
return shuffle(arr)
}
const addQuestionOutputHTML = question => {
output.innerHTML += question
return question
}
// () => string
const generateQuestion = pipe([
fork({
num: randomNum, // () => num
units: randomUnits, // () => shuffledArr
}), // () => { num, units }
({ num, units }) => `Convert ${num}${units[0]} to ${units[1]}`, // { num, units } => string
addQuestionOutputHTML, // string => string
])
generateQuestion() // => 'Convert 10mg/mL to mcg/mL'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.