jQuery 有没有办法比较 select 和 value 是不同类型的两个字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9461747/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 10:50:52  来源:igfitidea点击:

Is there a way to compare two strings where select and value are different types?

jquery

提问by ei.schinken

I'm having some problems to compare two strings in jQuery:

我在比较 jQuery 中的两个字符串时遇到了一些问题:

var option = "";
$.each(data, function(key, value) {
   option += "<option ";
   if(selected == value) {
      option += "selected";
   }
   option += ">" + value + "</option>";
});

selected and value are the same strings.

selected 和 value 是相同的字符串。

Is there an another way to compare two strings or could it be, that selected and value are different types?

是否有另一种方法来比较两个字符串,或者是否可以选择和值是不同的类型?

回答by mas-designs

You have to consider this:

你必须考虑到这一点:

The == operator compares two values and returns true if the values on both sides are equal to one another. If the two values have different data types (for example, if one is a number and the other is a text string) then they are both converted to the same type before the comparison takes place. JavaScript will convert whichever of the two types can be converted to the other type without having to change the value contained in the variable (for example, converting a number to a text string).

The === operator does the same thing with one minor difference. This operator does not convert data from one type to another. It only returns true when the variables being compared are both of the same type and contain the same value.

== 运算符比较两个值,如果两边的值彼此相等,则返回 true。如果两个值具有不同的数据类型(例如,如果一个是数字,另一个是文本字符串),则在进行比较之前,它们都将转换为相同的类型。JavaScript 将转换两种类型中的任何一种可以转换为另一种类型,而无需更改变量中包含的值(例如,将数字转换为文本字符串)。

=== 操作符做同样的事情,但只有一个细微的区别。此运算符不会将数据从一种类型转换为另一种类型。只有当被比较的变量都是相同的类型并且包含相同的值时,它才返回真。

回答by Lusaka Bhattacharyya

selected.substring(0,4)==value.substring(0,4)

回答by Astaroth

Have you tried the localeComparemethod?

你试过localeCompare方法吗?

if(selected.localeCompare(value) === 0) {
  . . . 
}

The method will return:

该方法将返回

  • 0:whenever the strings are equal
  • -1:if selectedis smaller than value
  • 1:if selectedis bigger than value
  • 0:当字符串相等时
  • -1:如果选择小于
  • 1:如果选择大于