Why .index () is resolved as a number in this expression, and .parent (). Index () resolving as string?

Here is the code, it refers to TD, and "farmland" is the table identifier:

$("#farmland td").click(function(){ $("#console").html($(this).index() + 1 + ", " + $(this).parent().index() + 1); }); 

When I press TD, I get 1.01 or 1.11 or 1.21, etc ... the number is correctly added for .index (), but for .parent (). index () is added 1 as if it were a string!

I thought that it was very curious, because I expected that it would either act in one way, or in another, and not in two different ways!

My first guess may be that it is because my + ", " + switches it to work as a string?

+4
source share
4 answers

This is because JavaScript sees the first call to index() , returning the number to which it adds the number 1, then you combine it with the string, so it combines the number into a string.

To add, regardless of strings, use parentheses to highlight numbers from strings:

 $("#farmland td").click(function(){ $("#console").html(($(this).index() + 1) + ", " + ($(this).parent().index() + 1)); }); 
+8
source

Whenever you want to force an estimate of var, you can do something like 1 * your_var and it will be interpreted as a number

0
source

He called the association from left to right.

0
source

Concatenation looks ugly when the best tools are available. What about:

 $("#farmland td").click(function(){ $("#console").html([$(this).index() + 1, $(this).parent().index() + 1].join(", ")); }); 
0
source

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


All Articles