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>
This is a standard JavaScript error when trying to call a function before it is defined. This error occurs if you try to execute a function that is not initialized or is not initialized correctly. This means that the expression did not return a function object.
JavaScript String indexOf() The indexOf() method returns the position of the first occurrence of a value in a string. The indexOf() method returns -1 if the value is not found. The indexOf() method is case sensitive.
To find the index of an object in an array, by a specific property: Use the map() method to iterate over the array, returning only the value of the relevant property. Call the indexOf() method on the returned from map array. The indexOf method returns the index of the first occurrence of a value in an array.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With