0

我正在尝试使用 phonegap 实现抖动检测,不幸的是,我遇到了一个问题,即返回未定义的值。

这是我的代码片段:

function acc() {
var accOpt = { frequency: 1000 };   
watchPot = navigator.accelerometer.watchAcceleration(win, fail, accOpt);    
}

function win (acceleration) {

    var tiltLR = 0;
    var tiltFB = 0;

    var facingUp = -1;
    if (acceleration.z > 0) {
      facingUp = +1;
    }

    tiltLR = Math.round(((acceleration.x) / 9.81) * -90);
    tiltFB = Math.round(((acceleration.y + 9.81) / 9.81) * 90 * facingUp);

      previousReading = {
        x   :   null,
        y   :   null,
        z   :   null,
        lr  :   null,
        fb  :   null            
      };

      var changes = {};

      if (previousReading.x !== null) {
          changes.x = Math.abs(previousReading.x-acceleration.x);
          changes.y = Math.abs(previousReading.y-acceleration.y);
          changes.z = Math.abs(previousReading.z-acceleration.z);
          changes.lr = Math.abs(previousReading.lr-tiltLR);
          changes.fb = Math.abs(previousReading.fb-tiltFB);
      }

      previousReading = {
          x: acceleration.x,
          y: acceleration.y,
          z: acceleration.z,
          lr: tiltLR,
          fb: tiltFB
      };


    console.log('previousReading x: ' + previousReading.x + ' previousReading y: ' + previousReading.y + ' previousReading z: ' + previousReading.z+ ' previousReading lr: ' + tiltLR + ' previousReading fb: ' + tiltFB);

    console.log('changes x: ' + changes.x  + ' changes y: ' + changes.y + ' changes z: ' + changes.z + ' changes lr: ' + changes.lr + ' changes fb: ' + changes.fb);

    console.log(acceleration.x + ' ' + acceleration.y + ' ' + acceleration.z);

 }

基本上,加速度 x、y、z 的值和先前读数的值都已正确记录在控制台中。

然而,问题在于changes.x、changes.y 和changes.z 的值,它们都出于某种原因返回未定义。

我也尝试检查 typeof(changes.x) 并且它也返回了 undefined 。

4

2 回答 2

3

根据您提供的代码,changes.x, changes.y并且changes.z未设置,因为 if (previousReading.x !== null) {将评估为 false,因为previousReading.x此处明确设置为 null:

 previousReading = {
    x   :   null,
    y   :   null,
    z   :   null,
    lr  :   null,
    fb  :   null            
  };
于 2012-12-31T10:46:05.333 回答
1

好吧,你正在使用整数,所以使用这个:

 previousReading = {
    x   :   0,
    y   :   0,
    z   :   0,
    lr  :   0,
    fb  :   0            
  };
于 2012-12-31T10:45:40.483 回答