為什么即使最小數字是 27 也顯示為 36
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相同
誰能解釋我為什么會發生這種情況以及如何解決這個問題
uj5u.com熱心網友回復:
您不是通過比較值來確定最小值,而是將min變數替換為陣列中小于50. 這可以修復如下:
let min = undefined;
for (let x in combination) {
if (combination[x] < 50) {
min = min == undefined ? combination[x] : Math.min(min, combination[x])
}
}
使用filterand reduce,這可以縮短很多:
combination.filter(x => x < 50).reduce((x, y) => Math.min(x, y))
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/435991.html
標籤:javascript php 数组 表现 lua
