...

View Full Version : parseInt method



Finch
12-16-2011, 07:44 AM
Im working on learning JavaScript with the help of a text book, below is the current script I am working on regarding handling forms. This script should populate the "Days" field depending on the Month selected. I understand most of it except for the parseInt function. Could anyone help describe it to me? I understand it turns a String into a Value...hmm



window.onload = initForm;

function initForm() {
document.getElementById("months").selectedIndex = 0;
document.getElementById("months").onchange = populateDays;
}

function populateDays() {
var monthDays = new Array(31,28,31,30,31,30,31,31,30,31,30,31);
var monthStr = this.options[this.selectedIndex].value;

if (monthStr != "") {
var theMonth = parseInt(monthStr);

document.getElementById("days").options.length = 0;
for(var i=0; i<monthDays[theMonth]; i++) {
document.getElementById("days").options[i] = new Option(i+1);
}
}
}



Thank you! I am very interested in learning this and would love any help!

Philip M
12-16-2011, 08:23 AM
Google is your friend!

http://www.w3schools.com/jsref/jsref_parseInt.asp


Quizmaster: In maths, what number is represented by 10 to the power of 3?
Contestant: Six.

Finch
12-17-2011, 01:51 AM
Yes, Google and I are friends. We get along quite well actually. I suppose I was just looking for a different explanation. But thanks for the comment.

Old Pedant
12-17-2011, 02:54 AM
I understand it turns a String into a Value...hmm

Well, yeah. Except a String *is* a Value.

It turns a string into an INTEGER value, if possible. Integers are whole numbers (-7, 55, 0, -113, 332, etc.). If the function can't convert the string to an integer, then the result is a special value called NaN ("Not a Number").

Compare parseInt() to parseFloat() andNumber( ).

html-tutorials
12-17-2011, 03:05 AM
basically, when something returned a number as a string, eg:



function something() { return "100"; }
var get = something();


You may not always want to use it as a string, if you need to do math:



var num = get + 1;
// at this point num wouldn't be 101... because you cant add a string to an integer and expect a mathematically correct result


However... the following solves the problem:



var num = parseInt(get) + 1;


Simple.

This can sometimes be common for parsing out a number out of a number+string combination with pixel values:



var width = "100px";
var new_width = parseInt(width) + 20;
var final = new_width + 'px';


The above will take 100px, remove "px" by parseInt, then add 20 to it, then re-ad "px"

This way you can do math on some default values stored in elements which do by default contain the dreaded PX.

felgall
12-17-2011, 05:08 AM
parseInt is for converting numbers between different bases. The original number can be in anything between base 2 (binary) and base 36. The result will always be base 10 (decimal). You can either specify the base the original number is in as the second parameter you supply to parseInt eg. parseInt('afbc91', 16) or have it assume what base you are translating from by the first character of the string - '0x' means base 16 and '0' means base 8.

To convert a string to a number use either:

var num = Number(str);

or

var num = +str;

Finch
12-17-2011, 08:24 AM
In the particular script above (I think this is where I am having trouble understanding the parseInt method), what is the parseint method doing? I will paste the HTML doc that goes along w. this below:



<!DOCTYPE html>
<html>
<head>
<title>Dynamic Menus</title>
<script src="script02.js"></script>
</head>
<body>
<form action="#">
<select id="months">
<option value="">Month</option>
<option value="0">January</option>
<option value="1">February</option>
<option value="2">March</option>
<option value="3">April</option>
<option value="4">May</option>
<option value="5">June</option>
<option value="6">July</option>
<option value="7">August</option>
<option value="8">September</option>
<option value="9">October</option>
<option value="10">November</option>
<option value="11">December</option>
</select>
&nbsp;

<select id="days">
<option>Day</option>
</select>
</form>

</body>
</html>


Thanks for all the help everyone, I am starting to understand it more - In this case, is the parseint is turning the var monthStr into a "number"? What does that actually do?

venegal
12-17-2011, 08:55 AM
Im working on learning JavaScript with the help of a text book

I'd ditch that text book, if I were you.

Trying to recreate date logic is pretty much always wrong, and should never be advocated in any learning material. There's already a built-in Date object, and not using it not only makes your code harder to maintain, it will most probably also result in a bunch of generalizations that just don't work in the real world:

February doesn't always have 28 days. Sometimes it has 29, and if you want to account for that fact in the piece of code you posted, you'll make the problem worse by introducing additional logic that the Date object already provides in the first place.

Since the Date constructor allows for overflowing values, the logic for determining the number of days in a certain month can be as simple as this:


function monthLength (year, month) {
return new Date(year, month + 1, 0).getDate();
}
alert(monthLength(2011, 1)); // 28
alert(monthLength(2012, 1)); // 29

Code that tries to mimic built-in date logic wastes a ridiculous amount of maintenance cost every year; I'm not nitpicking here — this is a real problem, and any text book that propagates this sort of DIY date logic without any regard to the big picture should be considered harmful.


And to answer your actual question: parseInt converts its argument to a string, discards everything that doesn't make sense for an integer, and returns a new primitive of type number. See here for how exactly that works: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/parseInt

That said, it's pretty much useless in your piece of code, since property names are strings anyway, so you're actually doing a double conversion:


for (var i in [0]) {alert(typeof i);} // string

Philip M
12-17-2011, 08:58 AM
To convert a string to a number use either:

var num = Number(str);

or

var num = +str;

Or var num = num*1;


The value returned from a select list value is a string value. But as I see it the values are not used in any case. The code is using selectedIndex which is already a number, so the parseInt() has no purpose in this case. Perhaps that is why you are having trouble understanding it.


Take a little time to study this code:-




<select id="months" onchange = "showValue()">
<option value="">Month</option>
<option value="0">January</option>
<option value="1">February</option>
<option value="2">March</option>
<option value="3">April</option>
</select>


<script type = "text/javascript">

function showValue() {
var myArray = ["Jan", "Feb", "Mar", "Apr"];
var val = document.getElementById("months").value;
alert (val + " " + typeof val);
alert (myArray[val]); // although val is a string value Javascript will interpret it as a number here
var si = document.getElementById("months").selectedIndex;
alert (si + " " + typeof si);
alert (myArray[si-1]);
var txt = document.getElementById("months").options[si].text;
alert (txt); // the text value of the option
}

As venegal says, that textbook seems less than instructive.

venegal
12-17-2011, 05:14 PM
The value returned from a select list value is a string value. But as I see it the values are not used in any case. The code is using selectedIndex which is already a number, so the parseInt() has no purpose in this case. Perhaps that is why you are having trouble understanding it.


This doesn't sound right. The value of the selected option is used — namely as an array key — whereas the selectedIndex property is only used to get that value (unnecessarily so, as pointed out in your snippet, since the value of the select itself can be used instead of the value of the selected option).

Also, this is a bit misleading:





alert (myArray[val]); // although val is a string value Javascript will interpret it as a number here



Internally, all property names (even numerical ones, i.e. array keys) are strings, so there's actually no type coercion going on here.

So, you're right that parseInt serves no purpose in the OP's code, but for the wrong reason: It's not that the thing is already a number — it's a string, and the reason parseInt is useless here is that a string is perfectly fine for accessing elements of an array.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum