Javascript 访问不断变化的变量赢得';t工作(约翰尼五杆)

Javascript 访问不断变化的变量赢得';t工作(约翰尼五杆),javascript,class,arduino,johnny-five,Javascript,Class,Arduino,Johnny Five,我正在用操纵杆做一个Arduino游戏。我有4个LED灯,每2秒,其中1个会亮起。使用操纵杆时,您必须尽可能快地做出反应以关闭LED灯。例如,如果左侧LED亮起,您必须在操纵杆上向左移动才能将其关闭 这是我的操纵杆的代码: var joystick = new five.Joystick({ pins: ["A0", "A1"], }); joystick.on("change", function() { let x = this.x; let y = this.y });

我正在用操纵杆做一个Arduino游戏。我有4个LED灯,每2秒,其中1个会亮起。使用操纵杆时,您必须尽可能快地做出反应以关闭LED灯。例如,如果左侧LED亮起,您必须在操纵杆上向左移动才能将其关闭

这是我的操纵杆的代码:

var joystick = new five.Joystick({
  pins: ["A0", "A1"],
 });

joystick.on("change", function() {
  let x = this.x;
  let y = this.y
 });
因此,每当操纵杆的位置发生变化时,
let x
let y
都会得到更新

现在我将向您展示函数的代码。此功能将每2秒重新启动一次。 问题是我需要操纵杆上的
let x
let y
使此功能工作, 但我不知道如何访问它们

const playGame = () => {
  setInterval(() => {
    console.log(x, y);
  }, 2000);
};

console.log(x,y)
导致
未定义

您需要在更改事件之外定义x和y,以便访问它

let x, y
var joystick = new five.Joystick({
  pins: ["A0", "A1"],
 });

joystick.on("change", function() {
  x = this.x;
  y = this.y
 });
const playGame = () => {
  setInterval(() => {
    console.log(x, y);
  }, 2000);
};
这是为了修复您的示例,但还有一种更为J5的方法(取自文档)

let x, y
var joystick = new five.Joystick({
  pins: ["A0", "A1"],
  freq: 100 // this limit the joystick sample rate tweak to your needs
});


joystick.on("change", function() { // only fire as the sample rate freq
  x = this.x;
  y = this.y
});

您需要在更改事件之外定义x和y,以便可以访问它

let x, y
var joystick = new five.Joystick({
  pins: ["A0", "A1"],
 });

joystick.on("change", function() {
  x = this.x;
  y = this.y
 });
const playGame = () => {
  setInterval(() => {
    console.log(x, y);
  }, 2000);
};
这是为了修复您的示例,但还有一种更为J5的方法(取自文档)

let x, y
var joystick = new five.Joystick({
  pins: ["A0", "A1"],
  freq: 100 // this limit the joystick sample rate tweak to your needs
});


joystick.on("change", function() { // only fire as the sample rate freq
  x = this.x;
  y = this.y
});

你能不能使用
this.x
this.y
?@Dhiraj这也会导致未定义的。
window.x
window.y
localStorage
你不能使用
this.x
this.y
?@Dhiraj这也会导致未定义的。
e访问全局变量的多种方法,
window.x
window.y
localStorage