Ter*_*ryO 22 javascript function indexof
我是JavaScript的新手,我收到如下错误.
未捕获的TypeError:time.indexOf不是函数
哎呀,我真的以为indexOf()确实是一个函数.这是我的代码片段:
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>
Run Code Online (Sandbox Code Playgroud)
Raj*_*amy 22
基本上indexOf()是一个属于字符串的方法(也是数组对象),但是在调用函数时,你传递一个数字,尝试将它转换为字符串并传递它.
document.getElementById("oset").innerHTML = timeD2C(timeofday + "");
Run Code Online (Sandbox Code Playgroud)
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+""));Run Code Online (Sandbox Code Playgroud)
在函数定义中进行字符串转换很好,
function timeD2C(time) {
time = time + "";
var pos = time.indexOf('.');
Run Code Online (Sandbox Code Playgroud)
因此,当开发人员忘记将字符串传递给此函数时,代码流不会中断.
小智 7
我收到e.data.indexOf is not a function错误,调试后发现它实际上是 a TypeError,这意味着,indexOf()作为一个函数适用于字符串,所以我像下面一样对数据进行类型转换,然后使用该indexOf()方法使其工作
e.data.toString().indexOf('<stringToBeMatchedToPosition>')
Run Code Online (Sandbox Code Playgroud)
不确定我的回答是否准确地回答了这个问题,但是当我面临类似的情况时,我分享了我的观点。
将timeofday转换为要使用的字符串 indexOf
var timeofday = new Date().getHours() + (new Date().getMinutes()) / 60;
console.log(typeof(timeofday)) // for testing will log number
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;
}
// "" for typecasting to string
document.getElementById("oset").innerHTML = timeD2C(""+timeofday);
Run Code Online (Sandbox Code Playgroud)
解决方案2
使用toString()转换为string
document.getElementById("oset").innerHTML = timeD2C(timeofday.toString());
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
99263 次 |
| 最近记录: |