Javascript indexOf 不是函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39821472/
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
indexOf is not a function
提问by Devil Raily
I' am currently working with the following code. In the console it's throwing
我目前正在使用以下代码。在控制台中它正在抛出
Uncaught TypeError: TotalAccountBalance.indexOf is not a function
未捕获的类型错误:TotalAccountBalance.indexOf 不是函数
I don't know what else to do. Searching didn't 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('console.log( TotalAccountBalance.toString().indexOf('.') );
.00');
$('#total-account-balance').val('TotalAccountBalance = +CurrentPreservedBalance + +CurrentGeneralAccountBalance;
.00');
}
回答by Andy Ray
回答by Quentin
(TotalAccountBalance + "").indexOf('.')
TotalAccountBalance = +CurrentPreservedBalance + +CurrentGeneralAccountBalance;
TotalAccountBalanceis the result of taking two numbers (we know they are numbers because you used the unary plus operator to convert them) and addingthem together. This is another number.
TotalAccountBalance是取两个数字(我们知道他们的数字,因为你使用的一元加运算,将它们转换),将结果加在一起。这是另一个数字。
indexOfis a method that you find on stringsnot numbers.
indexOf是您在字符串而不是数字上找到的方法。
You could convert to a string:
您可以转换为字符串:
console.log( ("" + TotalAccountBalance).indexOf('.') );
回答by lonesomeday
The unary plus operatorsconvert the strings into numbers; this is obviously desirable behaviour in order to get the correct mathematical result.
在一元加运算符转换字符串成数字; 为了获得正确的数学结果,这显然是理想的行为。
If you then want to use a string function (e.g. indexOf), you need to convert back to a string:
如果您想使用字符串函数(例如indexOf),则需要转换回字符串:

