Uncaught TypeError:.indexOf不是一个函数 [英] Uncaught TypeError: .indexOf is not a function
问题描述
$ b
未捕获的类型错误: time.indexOf不是函数
啧啧,我真的以为indexOf()确实是一个函数。这里是我的代码片段:
var timeofday = new Date()。getHours()+(new Date()。 getMinutes())/ 60;
document.getElementById(oset)。innerHTML = timeD2C(timeofday);
< / script>
< script>
函数timeD2C(time){//将11.5(十进制)转换为11:30(冒号)
var pos = time.indexOf('。');
var hrs = time.substr(1,pos - 1);
var min =(time.substr(pos,2))* 60;
if(hrs> 11){
hrs =(hrs - 12)+:+ min +PM;
} else {
hrs + =:+ min +AM;
}
return hrs;
}
< / script>
基本上 indexOf()
是一个属于字符串(数组对象也)的方法,但是当你调用函数传递一个数字时,尝试将它转换为一个字符串并传递它。
document.getElementById(oset)。innerHTML = timeD2C(timeofday +);
var timeofday = new Date()。getHours()+(new Date()。getMinutes())/ 60;函数timeD2C(time){//将11.5(十进制)转换为11:30(冒号)var pos = time.indexOf('。'); var hrs = time.substr(1,pos - 1); var min =(time.substr(pos,2))* 60; if(hrs> 11){hrs =(hrs-12)+:+ min +PM; } else {hrs + =:+ min +AM;
$> $> hr>
在函数定义中进行字符串转换是很好的做法,
function timeD2C(time){
time = time +;
var pos = time.indexOf('。');
因此,当开发人员忘记将字符串传递到此函数时,代码流不会中断。
I am new to JavaScript and I'm getting an error as below.
Uncaught TypeError: time.indexOf is not a function
Gee, I really thought indexOf() really was a function. Here is a snippet of my code:
var timeofday = new Date().getHours() + (new Date().getMinutes()) / 60;
document.getElementById("oset").innerHTML = timeD2C(timeofday);
</script>
<script>
function timeD2C(time) { // Converts 11.5 (decimal) to 11:30 (colon)
var pos = time.indexOf('.');
var hrs = time.substr(1, pos - 1);
var min = (time.substr(pos, 2)) * 60;
if (hrs > 11) {
hrs = (hrs - 12) + ":" + min + " PM";
} else {
hrs += ":" + min + " AM";
}
return hrs;
}
</script>
解决方案 Basically indexOf()
is a method belongs to string(array object also), But while calling the function you are passing a number, try to cast it to a string and pass it.
document.getElementById("oset").innerHTML = timeD2C(timeofday + "");
var timeofday = new Date().getHours() + (new Date().getMinutes()) / 60;
function timeD2C(time) { // Converts 11.5 (decimal) to 11:30 (colon)
var pos = time.indexOf('.');
var hrs = time.substr(1, pos - 1);
var min = (time.substr(pos, 2)) * 60;
if (hrs > 11) {
hrs = (hrs - 12) + ":" + min + " PM";
} else {
hrs += ":" + min + " AM";
}
return hrs;
}
alert(timeD2C(timeofday+""));
And it is good to do the string conversion inside your function definition,
function timeD2C(time) {
time = time + "";
var pos = time.indexOf('.');
So that the code flow won't break at times when devs forget to pass a string into this function.
这篇关于Uncaught TypeError:.indexOf不是一个函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!