2015-04-12 66 views
0

在我的角度应用程序中,我使用循环在对象中查找给定数字的最近值并返回其密钥。JSLint:如何不在循环内使这个函数

例如,我想最接近值0.5:

for (var j in nums) { 
     if (0.5 > nums[j]) var prev = nums[j]; 
     else if (0.5 <= nums[j]) { 
     // If the current number is equal to 0.5, or immediately higher, stores that number 
     // and stops the for each() loop 
     var next = nums[j]; 
     // Get the value 
     var percentage = (Math.abs(0.5 - prev) < Math.abs(next - 0.5)) ? prev : next; 
     // Get the key from the value 
     $scope.seventyfive = parseInt('0' + Object.keys(nums).filter(function(key) {return nums[key] === percentage;})[0], 10); 
     break; 
     } 
    } 

JSLint的是指出,我不应该在一个循环中做功能,所以我试图避免与:

filterPct = function (nums, pct) { 
     return function() { 
     return nums[key] === pct; 
     }; 
    } 

for (var j in nums) { 
     if (0.5 > nums[j]) var prev = nums[j]; 
     else if (0.5 <= nums[j]) { 
     // If the current number is equal to 0.5, or immediately higher, stores that number 
     // and stops the for each() loop 
     var next = nums[j]; 
     // Get the value 
     var percentage = (Math.abs(0.5 - prev) < Math.abs(next - 0.5)) ? prev : next; 
     // Get the key from the value 
     $scope.seventyfive = parseInt('0' + Object.keys(nums).filter(filterPct(nums, percentage))[0], 10); 
     break; 
     } 
    } 

但这返回0,而不是正确的值。我肯定我失去了一些东西很明显,但我显然需要另一双眼睛......

UPDATE:感谢给了我支持,这是代码的防错以上版本:

filterPct = function (nums, pct) { 
     return function (key) { 
     return nums[key] === pct; 
     }; 
    }; 

    // Store the value with 50% Confidence 
    for (i in nums) { 
     if (nums.hasOwnProperty(i)) { 
     if (0.5 > nums[i]) { 
      prev = nums[i]; 
     } else if (0.5 <= nums[i]) { 
      // If the current number is equal to 0.5, or immediately higher, stores that number 
      // and stops the for each() loop 
      next = nums[i]; 
      // Get the value 
      percentage = (Math.abs(0.5 - prev) < Math.abs(next - 0.5)) ? prev : next; 
      // Get the key from the value 
      $scope.fifty = parseInt('0' + Object.keys(nums).filter(filterPct(nums, percentage))[0], 10); 
      break; 
     } 
     } 
    } 
+1

“JSLint指出我不应该在一个循环内创建函数” - 这是因为它很容易创建意外关闭。你正在使用函数*立即*,这不是一个问题在这里。 – Quentin

回答

1
filterPct = function (nums, pct) { 
    return function() { 
     return nums[key] === pct; 
    }; 
} 

你忘了定义key(应该是内部函数的第一个参数)。