| Home | Register | FAQ | Members List | Search | Today's Posts | Mark Forums Read |
|
|
#1 (permalink) |
|
shiro
Join Date: Aug 2007
Location: Yokohama, Japan
Posts: 2,545
|
javascript data type question
I put together a DOM script for my company the other day. While doing it, I ran into a data-type problem. I know enough to know that my datatypes were wrong (or at least I figured that out), and I figured out how to convert them to the same datatype in order to make it work, but I don't know enough to know what the original datatypes were. I had one function called from two places. In the function was a 'switch'. One variable, a number, was passed to the function, and then that variable was used to execute the switch statement. I got the variable passed to the function in two different ways. The first way was through a for loop. Code:
I was the variable I passed to the function. The other one I got was through a drop down menu. I wont put the whole code in here, but I had a <select>tag with some <options> tags in it, and the value for each of the <option> tags was a number. This time I called the function using the onclick event listener in the <select> tag. I passed the value of this.value to the function. So in the first case, I was passing 'i', in the second case I was passing 'this.value' from a select tag. The datatypes didn't match. I eventually got around the problem by converting both to text, and converting the number values in the 'switch' statement to strings. It worked, but as I say, I don't think it was ideal. So my questions: 1) What were my datatypes from these two methods? 2) How could I have converted each of them to the other data type? Thanks to anyone who answers this! As I say, its not imperative in that I have already found a work around, but I want to understand better so that I can become a better programmer. |
|
|
|
|
|
#2 (permalink) |
|
Grumpy old man
Join Date: Oct 2007
Location: North Japan
Posts: 1,672
|
Forgive me if I've misunderstood your questions. Your initial explanation was a bit hard to follow. 1. The original data types In the loop example, i is a Number (there are no specific int or float types in javascript). In the select tag example, it's a String, even though it is a numeric character. You can check this if you want with the following: Code:
(the typeof operator returns the data type of its operand) 2. Conversion The easiest way to convert types in Javascript is to simply use the constructor called as a function, e.g. Code:
These aren't terribly efficient methods and there are other ways. For example you can convert a string to a number by performing a non-value-altering mathematical operation on it such as: Code:
Or you could turn a number into a string by using the concatenation operator: Code:
I'm sure you can come up with a number of other ways, these are just a few. |
|
![]() |