gpt4 book ai didi

javascript - JSLint:如何不在循环中使用此函数

转载 作者:行者123 更新时间:2023-12-03 10:21:58 25 4
gpt4 key购买 nike

在我的 Angular 应用程序中,我使用循环在对象中查找最接近给定数字的值并返回其键。

例如,我想要最接近 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 而不是正确的值。我确信我错过了一些明显的东西,但我显然需要另一双眼睛......

更新:感谢我收到的支持,这是上面代码的防错版本:

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;
}
}
}

最佳答案

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

您忘记定义key(它应该是内部函数的第一个参数)。

关于javascript - JSLint:如何不在循环中使用此函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29587540/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com