当我使用变量进行比较时,Javascript小于失败

时间:2014-12-03 12:45:40

标签: javascript variables comparison-operators

我有两个'如果少于'当我将比较的右手边从Math.PI替换为我的变量this.bottomChainAngleRads时,似乎对我不起作用的块。

背景:我在两个齿轮之间设置链条的动画,因此在两个齿轮的齿上迭代以隐藏/显示它们旋转时的链接

在代码的早期,变量是用math而不是字符串初始化的。

this.bottomChainAngleRads = Math.PI + 2 * Math.atan2(...);

然后我想偶尔做一些事情:

this.step = function() {
  console.log('this.bottomChainAngleRads = ' + this.bottomChainAngleRads  // Just over PI. Usually about 3.4.
              + ' ' + $.isNumeric(this.bottomChainAngleRads));            // Always true.

  // Counting the passing through each if block. Expecting a little in each.
  var frontDisplay = 0, frontHide = 0, rearDisplay = 0, rearHide = 0;

  $(this.frontGear.div).find('.geartooth').each(function(index, el) {
    var totalRadians = measureRotation(el);
    console.log('front totalRadians = ' + totalRadians + ' '    // From 0 to TWO_PI
                + (totalRadians < this.bottomChainAngleRads));  // Always false. WTF.
    if (totalRadians < this.bottomChainAngleRads) { // <================ FAILS. NEVER TRUE.
    // if (totalRadians < Math.PI) { // MOSTLY CORRECT, but expectedly off by minor angle.
      ++frontDisplay;
      // .. do stuff
    } else {
      ++frontHide;
      // .. do other stuff
    }
  });

  $(this.rearGear.div).find('.geartooth').each(function(index, el) {
    var totalRadians = measureRotation(el);
    console.log('rear totalRadians = ' + totalRadians + ' '     // From 0 to TWO_PI
                + (totalRadians < this.bottomChainAngleRads));  // Always false. WTF.
    if (totalRadians < this.bottomChainAngleRads) { // <================ FAILS. NEVER TRUE.
    // if (totalRadians < Math.PI) { // MOSTLY CORRECT, but expectedly off by minor angle.
      ++rearHide;
      // .. do stuff
    } else {
      ++rearDisplay;
      // .. do other stuff
    }
  });

  // Below I expected approximately a 50/50 split on each gear.  Instead, I get...
  console.log('front: ' + frontDisplay + ', ' + frontHide     // Nothing, All.
              + '; rear: ' + rearDisplay + ', ' + rearHide);  // All, Nothing
}

对于详细的代码感到抱歉,但是因为我觉得我已经尝试了很多东西,所以我想提供更大的图片。

1 个答案:

答案 0 :(得分:0)

each回调中的上下文不再是您的对象实例,this指向单个DOM元素(.geartooth),这显然没有属性{{1 }}

最简单的解决方法是保存正确的上下文引用。试试这个:

bottomChainAngleRads