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;
}
}
}
「JSLint指出我不應該在一個循環內創建函數」 - 這是因爲它很容易創建意外關閉。你正在使用函數*立即*,這不是一個問題在這裏。 – Quentin