簡體   English   中英

誰能告訴我為什么在嘗試調用此函數時會出錯?

[英]Can anyone tell me why I get a error when i try to call this function?

<!doctype html>
<html>
<script>
function isNumber(value) {
    return typeof (value) != "boolean" && !isNaN(value) && value.length > 0;
}

function minMaxDefrost(value, min, max) {

    if (value.length == 0 || value == "-") return value;
    if (!isNumber(value)) return value.substring(0, value.length - 1);
    
console.log("minMaxDefrost called ")
    if (parseFloat(value) < min){
        return min;
        }
    else if (parseFloat(value) > max){
        return max;
        }
    else {
        return Math.floor(value);
    }
}


minMaxDefrost(4, 0, 12);

</script>
</html>
  • 我在 html keyup 函數中使用此函數,它工作正常,但是當我嘗試在代碼開頭自行調用它時,我收到錯誤消息 Uncaught TypeError: value.substring is not a function
  • 也不是當我從 keyup 調用這個函數時,我使用“this.value = minMaxDefrost(this.value, -80, 150, 0)
  • 我假設錯誤與 this.value 有關,但我不知道如何修復它

isNumber(4)計算結果為false ,因此您嘗試在4上調用substring方法,但該方法不存在。 使用typeof value === 'number'來測試某個東西是否是數字。 或者更好的是,在將它視為絕對是字符串之前使用typeof value === 'string'

isNumber並沒有像 Mark Hanna 建議的那樣完全完成它的工作......更好的isNumber應該是這樣的

function isNumber(num){
  let num1=num-0, num2=num-1
  return num2!=num1 && !!(num2||num1) && typeof(num)!="object"
  //Infinity would fail the test num2!=num1
  //Normal non-numbers would fail !!(num2||num1)
  //null would fail typeof(null)!="object"
  //However, 0, and even "0" will pass this test
}

這是您提供給我們的代碼中返回的

 function isNumber(num){ let num1=num-0, num2=num-1 return num2!=num1 && !!(num2||num1) && typeof(num)!="object" //Infinity would fail the test num2!=num1 //Normal non-numbers would fail !!(num2||num1) //null would fail typeof(null)!="object" //However, 0, and even "0" will pass this test } function minMaxDefrost(value, min, max) { if (value.length == 0 || value == "-") return value; if (!isNumber(value)) return value.substring(0, value.length - 1); console.log("minMaxDefrost called ") if (parseFloat(value) < min){ return min; } else if (parseFloat(value) > max){ return max; } else { return Math.floor(value); } } minMaxDefrost(4, 0, 12);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM