2016-01-29 48 views
1

我不清楚下面的代码究竟出了什么问题。
我想要求用户输入一个文本字符串并将其与另一个文本字符串进行比较。然后通知用户他的字符串是否按字母顺序高于或低于存储值。当我在jsfiddle中测试时,我只能得到第二条警告消息。为什么会发生?Javascript字符串比较显示不正确的结果

这是我的代码:

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"); 
+1

可能的复制(http://stackoverflow.com/questions/10198257/comparing-2-strings-alphabetically-for-sorting-purposes) – Oxi

回答

1

你不是在所有比较的变量,但实际字符串“字符串1” &“字符串2”。这就是为什么你总是得到第一个警报,因为"string1" > "string2" lexicographicaly(按字母顺序)。

用途:

if (string1 > string2) 

这将解决您的代码,使其工作,但在JavaScript中比较字符串一个更安全,更好的办法是使用localeCompare

string1.localeCompare(string2); 

/* Returns: 

0: equal 

-1: string1 < string2 

1: string1 > string2 

*/ 
+1

由于IDOS ..认为这将是微不足道的。会尝试localeCompare,thx! – whada

+0

没问题@whada,很高兴能帮到你 – Idos

0

如果去掉周围的变量名引号,它会工作作为标榜。否则你是比较两个字符串,并从不检查变量。

因为“字符串1”>“字符串2”简直是总是假的,你总是会进入else块在你的代码已经发布

0

正如IDOS提到,你创建了两个新的字符串,并在你的if语句中进行比较,而不是用户的要求。的[按字母顺序比较2个字符串排序目的]

"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"