简体   繁体   English

如何在JavaScript中正确比较2个字符串?

[英]How to properly compare 2 strings in JavaScript?

I am absolutely new in JavaScript and I have a problem comparing 2 strings. 我绝对不是JavaScript新手,比较2个字符串时遇到问题。

Into a function I have this code: 进入函数我有以下代码:

var selectedProjectStatusText = selectedProjectStatus.options[selectedProjectStatus.selectedIndex].text;

alert("== " + selectedProjectStatusText == "-- Please Select --");
alert("=== " + selectedProjectStatusText === "-- Please Select --");

I am using the alert() function to try how to work string comparator. 我正在使用alert()函数尝试如何使用字符串比较器。

The problem is that both the alert() say me FALSE when the selectedProjectStatusText variable contains the -- Please Select -- string. 问题是,无论是alert()说我假,当selectedProjectStatusText变量包含-- Please Select --字符串。

Why? 为什么? What am I missing? 我想念什么? what could be the cause of the problem? 可能是什么原因造成的? How can I fix it? 我该如何解决? What am I missing? 我想念什么?

You need to remove "=== " + from the start of your conditional statement, or wrap in parenthesis "=== " + (condition) try this instead: 您需要从条件语句的开头删除"=== " + ,或将括号括起来在"=== " + (condition)尝试以下操作:

alert(selectedProjectStatusText == "-- Please Select --");

http://jsfiddle.net/eceb5bpx/ http://jsfiddle.net/eceb5bpx/

If you are wanting to see if the string contains '-- Please Select --' then your condition is incorrect and you should instead use 如果要查看字符串是否contains “-请选择-”,则说明您的条件不正确,应改用

alert(string.indexOf('-- Please Select --') > -1);

Try putting your condition in parentheses so that it's evaluated before string concatenation. 尝试将条件放在括号中,以便在字符串连接之前对其进行评估。

 var selectedProjectStatusText = "-- Please Select --"; alert("== " + (selectedProjectStatusText == "-- Please Select --")); alert("=== " + (selectedProjectStatusText === "-- Please Select --")); 

You could use the JS concat() function to display the results of your comparison in the format you are using: 您可以使用JS concat()函数以使用的格式显示比较结果:

See JSFiddle 参见JSFiddle

var selectedProjectStatusText = "-- Please Select --";
alert("== ".concat(selectedProjectStatusText == "-- Please Select --"));
alert("=== ".concat(selectedProjectStatusText === "-- Please Select --"));

"==" : equal to, while "===" : equal value and equal type “ ==”:等于,而“ ===”:等于值和等于类型

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM