IndexOf is not a function

I am currently working with the following code. In the console, he throws

Uncaught TypeError: TotalAccountBalance.indexOf is not a function

I do not know what else to do. The search did not help much.

var CurrentPreservedBalance, CurrentGeneralAccountBalance, TotalAccountBalance; CurrentPreservedBalance = '20.56'; CurrentGeneralAccountBalance = '20.56'; if( CurrentPreservedBalance && CurrentGeneralAccountBalance ){ TotalAccountBalance = +CurrentPreservedBalance + +CurrentGeneralAccountBalance; console.log( TotalAccountBalance.indexOf('.') ); } else { $('#total-fnpf-account-balance').val('$0.00'); $('#total-account-balance').val('$0.00'); } 
+5
source share
3 answers

indexOf() is a method of strings, not numbers.

 console.log( TotalAccountBalance.toString().indexOf('.') ); 
+7
source
 TotalAccountBalance = +CurrentPreservedBalance + +CurrentGeneralAccountBalance; 

TotalAccountBalance is the result of accepting two numbers (we know that they are numbers because you used the unary plus operator to convert them) and adding them together. This is another number.

indexOf is a method that you will find in non- number strings .

You can convert to string:

 (TotalAccountBalance + "").indexOf('.') 
+2
source
 TotalAccountBalance = +CurrentPreservedBalance + +CurrentGeneralAccountBalance; 

Unary plus operators convert strings to numbers; this is obviously the desired behavior in order to get the correct mathematical result.

If you want to use a string function (e.g. indexOf ), you need to convert it back to a string:

 console.log( ("" + TotalAccountBalance).indexOf('.') ); 
+1
source

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


All Articles