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

I am having trouble matching two strings in jQuery:

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

and the values ​​are the same lines.

Is there any other way to compare two strings, or maybe the selected and the values ​​are different types?

+4
source share
3 answers

You must consider this:

The == operator compares two values ​​and returns true if the values ​​on both sides are equal to each other. If two values ​​have different values, data types (for example, if it is a number, and the other is text string), then they are both converted to the same type before the comparison happens. JavaScript converts either of the two types can be converted to another type without changing the value contained in the variable (for example, converting a number to a text string).

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

+23
source
 selected.substring(0,4)==value.substring(0,4) 
0
source

Have you tried the localeCompare method?

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

The method returns :

  • 0: when the lines are equal
  • -1: if less than selected
  • 1: if more value is selected
0
source

Source: https://habr.com/ru/post/1398559/


All Articles