當我將Math.PI的比較右側替換爲我的時候,我有兩個'if less then'塊似乎不適合我變量,this.bottomChainAngleRads。當我使用一個變量進行比較時,Javascript比這個失敗了
語境:我動畫鏈兩個齒輪之間,所以迭代的兩個齒輪隱藏/顯示它的鏈接,他們旋轉
代碼早些時候,該變量初始化所用牙齒數學,而不是一個字符串。
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
}
對不起,冗長的代碼,而是因爲我覺得我已經嘗試了這麼多東西,我想給更大的圖片。
這是一個範圍問題。 '.each'裏面的'this'是指DOM元素而不是你的對象。在'.each'之外使用'var that = this',然後使用'that'適當的 – devnull69 2014-12-03 12:49:04