javascript - 我的变量是作用域的,我需要它是全局的
问题描述
嗨,所以我是这个基本的新手,在我自己看了相当多的时间后寻求帮助。
我正在玩具编程一个游戏,我使用智能手机的方向来触发事件。我的问题是我无法获得变量值,这似乎遥不可及。如果我将函数的参数发送给彼此,游戏运行良好,但如果我需要更改全局变量以便我可以轻松使用它。
- 看来我的变量是作用域的,我不明白我该如何帮助它。
- 在下面的示例中,如何使 beta 变量成为全局变量?
- 变量的作用域是因为 if 语句、=> 还是 .then?
//The variable pression is the one I need to be global
let beta, gamma, pression=0, gameover=false, audio_source;
//displaying banner to authorize DeviceOrientationEvent on mobile
function bannerAuthorisation() {
if (window.DeviceOrientationEvent && typeof window.DeviceOrientationEvent.requestPermission === 'function'){
const banner = document.createElement('div');
banner.innerHTML = `<div id="autorisation" style="z-index: 1; position: absolute; width: 100%; background-color:#000; color: #fff" onclick="clickRequestDeviceOrientationEvent();"><p style="padding: 10px">Cliquez ici pour autoriser l'accès à votre capteur de mouvements.</p></div>`;
document.querySelector('body').appendChild(banner)
} else {
alert("Sorry you cannot play");
}
}
//If permission to play with DeviceOrientationEvent is granted, then I fetch beta and gamma
function clickRequestDeviceOrientationEvent() {
window.DeviceOrientationEvent.requestPermission()
.then(response => {
if (response === 'granted') {
window.addEventListener('deviceorientation', (e) => {
document.getElementById('autorisation').style.display = 'none';
//normalizing beta and gamma values and assigning it to global variables
beta=(Math.round(e.beta));
gamma=(Math.round(e.gamma));
//Here I send those values to another function and I can use it
increasePression();
}
)} else {
alert("Sorry you need to authorize the game to use it.")
}
})
.catch(e => {
console.error(e)
})
}
//Here I try to display the beta variable in HTML and it fails
//because I did not send params from above hte function above and it seems my var is not global
function test (){
document.getElementById("stuff").innerHTML = beta;
}
解决方案
推荐阅读
- python - Kubernetes spark-submit on ADLS Gen2 错误:找不到类 org.apache.hadoop.fs.azurebfs.SecureAzureBlobFileSystem
- javascript - 如何从二维数组中获取列“b”的值,其中列“a”与javascript中的单个数组匹配
- asp.net-core - .NET 5 API 添加 Access-Control-Allow-Origin 标头 - 使用 Ionic 5.5
- google-chrome - Google Chrome 浏览器 - 搜索时返回页面中的开始搜索位置
- react-native - react-native-fs 在模拟器上有效但在实际设备上无效的可能原因
- javascript - 如何将卡尔曼滤波器与旋转对象一起使用
- c++ - 如何验证类成员函数是内联函数?
- reactjs - rc-datepicker DatePickerInput 图标没有出现
- flutter - Flutter:Android模拟器内存不足
- java - 在 Spring MVC 中获取 HttpServletRequest