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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 22:55:57  来源:igfitidea点击:

indexOf is not a function

javascript

提问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

indexOf()is a method of Strings, not Numbers.

indexOf()是字符串的方法,而不是数字。

TotalAccountBalance = +CurrentPreservedBalance + +CurrentGeneralAccountBalance;

回答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),则需要转换回字符串:

##代码##