[英]Javascript string comparing not showing correct result
我不清楚下面的代碼到底有什么問題。
我想請用戶輸入一個文本字符串,並將其與另一個文本字符串進行比較。 然后,通知用戶他的字符串是按字母順序高於還是低於存儲值。 當我在jsfiddle中測試時,我僅收到第二條警報消息。 為什么會這樣?
這是我的代碼:
var string1;
var string2;
string1 = prompt("Tell me your string1?");
string2 = "green";
if ("string1" > "string2")
alert("Your string is alphabetically higher");
else
alert("Your string is not alphabetically higher");
您根本不需要比較變量,而是實際的字符串“ string1”和“ string2”。 這就是為什么您總是收到第一個警報的原因,因為"string1" > "string2"
按字典順序(字母順序)。
采用:
if (string1 > string2)
這樣可以修復您的代碼並使之正常工作,但是在javascript中比較字符串的一種更安全更好的方法是使用localeCompare
:
string1.localeCompare(string2);
/* Returns:
0: equal
-1: string1 < string2
1: string1 > string2
*/
localeCompare()方法返回一個數字,該數字指示參考字符串是按排序順序位於給定字符串之前還是之后還是與之相同。
string1.localeCompare(string2)
如果您刪除變量名周圍的引號,它將按照廣告中的說明工作。 否則,您將比較兩個字符串,並且從不檢查變量。
由於“ string1”>“ string2”始終始終為false,因此您始終會進入已發布代碼中的else塊
var stringA = 'something';
var stringB = 'foobar';
var compareResult = stringA.localeCompare(stringB);
if (compareResult < 0) {
console.log('a is before b');
} else if (compareResult > 0) {
console.log('a is after b');
} else {
console.log('a equals b');
}
正如Idos所提到的,您正在創建兩個新字符串,並在if語句中而不是在用戶詢問的字符串中進行比較。
"string1" > "string2"
// This compares the values "string1" and "string2"
string1 > string2
// This compares the contents of the variables string1 and string2,
// in your case the user input and "green"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.