为什么 JavaScript 表现不同

why JavaScript is behaving differently

为什么它显示 36,即使最小数字是 27

   var combination = [27, 36]
    
    for (let x in combination) {
        if (combination[x] < 50) {
            var min = Math.min(combination[x])
        }
    }
    
    console.log(min)

我尝试了多种方法,例如

    var combination = [27, 30, 40, 44, 3, 239, 329, 2, 5, 20923, 96]
    
    for (let x in combination) {
        if (combination[x] < 50) {
            var min = Math.min(combination[x])
        }
    }
    
    console.log(min) //output--  5         //it should be 2

在第三个示例中,我将 (-) 添加到 2

var combination = [27, 30, 40, 44, 3, 239, 329, -2, 5, 20923, 96]

for (let x in combination) {
    if (combination[x] < 50) {
        var min = Math.min(combination[x])
    }
}

console.log(min) // output-- still 5     // it should be -2 

再次当我将 (-) 添加到其他数字(如 -96 或 -5)时,输出没问题(-96),但是当我将(-)添加到 2 时,它并没有在输出中显示 -2它显示 5

不仅在 javascript 中,我用 lua、php 尝试过,但输出与 js

相同

谁能解释一下为什么会这样以及如何解决这个问题

您不是通过比较值来确定最小值,而只是将 min 变量替换为数组中小于 50 的最后一个数字。这可以按如下方式修复:

let min = undefined;
for (let x in combination) {
    if (combination[x] < 50) {
        min = min == undefined ? combination[x] : Math.min(min, combination[x])
    }
}

使用filterreduce,可以缩短很多:

combination.filter(x => x < 50).reduce((x, y) => Math.min(x, y))