值返回为Undefined

时间:2012-12-31 10:42:44

标签: javascript jquery cordova jquery-mobile

我正在尝试使用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的值和先前读数的值正在控制台中正确记录。

然而问题是change.x,changes.y和changes.z的值,由于某种原因都返回undefined。

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

2 个答案:

答案 0 :(得分:3)

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

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

答案 1 :(得分:1)

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

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