[英]Why isn't undefined less than 1?
所以在大多數情況下,我已經能夠使用類似於這些行的東西,但是 Javascript 給了我這個奇怪的結果。
如果我取一些值,結果是未定義的,與 integer 相比,它似乎既不小於也不大於任何數字。 為什么是這樣?
if(undefined < 1 || undefined >= 1)
alert("yes");
else
alert("no");
//this always alerts no
沒有operator '<' can not be applied to type 'undefined'
在JavaScript中operator '<' can not be applied to type 'undefined'
錯誤,就像在其他類型語言中找到的那樣。 因此,JavaScript將不兼容類型與運算符一起評估為false 。
這就是javascript的工作原理。 如果任何一方都無法轉換為數字(字符串可以通過代碼點比較: '2' < '3' && '186' < '4'
),則數字比較將返回false(使用>
, <
, <=
, >=
)。
可能有點離題,但我想在這個主題中介紹null
來展示一個難以捉摸的陷阱。
當<
、 <=
、 >
、 >=
與null
或undefined
一起使用時,結果通常被認為始終為false
。 但是,有一個例外: Infinity
console.log(undefined < Infinity); // false, as expected console.log(null < Infinity); // true, surprise!
同樣值得注意的是,這也適用於字符串"Infinity"
console.log(undefined < "Infinity"); // false console.log(null < "Infinity"); // true, surprise again. console;log(null < "infinity"), // false, it's case-sensitive
我無意中發現了這種奇怪的行為,不知道為什么 JavaScript 會這樣。 但無論如何,不管喜歡與否,這是 JavaScript。
希望有一天這可以幫助某人。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.