JavaScript - Differences Between String > Number Conversions
A week or so ago Old Pedant and I discussed methods of converting string inputs to numbers. I speculated that *1 might be quicker. I have now run a test:-
Code: <script type = "text/javascript"> var start = new Date().getTime(); for (var i =0; i <100000; i++) { var a = "2"; a = a *1; } var end = new Date().getTime(); var diff1 = end - start; alert (diff1); // 109 var start = new Date().getTime(); for (var i =0; i <100000; i++) { var a = "2"; a = parseInt(a); } var end = new Date().getTime(); var diff2 = end - start; alert (diff2); // 140 var start = new Date().getTime(); for (var i =0; i <100000; i++) { var a = "2"; a =Number(a); } var end = new Date().getTime(); var diff3 = end - start; alert (diff3); // 140 var start = new Date().getTime(); for (var i =0; i <100000; i++) { var a = "2"; a = +a; } var end = new Date().getTime(); var diff4 = end - start; alert (diff4); // 109 </script> The results vary slightly with each run, but the conclusion is that there is no real difference between the methods - except for a = a*1 and a = +a which consistently comes in lower than parseInt() or Number(). But the differences are too small to be significant. Similar TutorialsWhen I used toFixed() method on a number, I thought that this method round a number to a specified approximation, but I got a surprising result, the number became string! 15.23689 .toFixed ( 2 ) ==> "15.24" So does it convert the number into string? Hi, I have a string stored in a variable var = "4.25 houses". I would like to only extract the currency value, ie "4.25" from this. Is this possible? Also I would like to divide and multiply the new variable I get... does this number need to be converted or something? Thanks in advance! I need to check if a var (lessonnum) is a string that cannot be converted to a number, i.e. "fred" "george" "catalyst" etc. but not "5" "456" or "34564" etc.: Code: var lessonnum = readCookie('lesson'); if ((intro != "12")||((lessonnum != "A STRING THAT COULD BE A NUMBER"))){ do sth. } How could I do that? I have an Adobe pdf fill-able form field that requires a distance computation using javascript. One of the values needed in the computation is in the format of a string as feet - inches (for example: 4'-10"). I need to convert this into a number to use to complete a computation. Does anyone have a code snippet or any ideas on how to do this. Any assistance is greatly appreciated. Thanks. I have a string of text, and starting from a particular spot (known to be a number), I want to find the length of that number. Here's what I have: Code: ... var start = [...predetermined...] var end = 0; while (!isNaN(sourceCode.charAt(start + end))){ endCurrent++; } var myNum = sourceCode.substr(start, end) * 1; So let's say var sourceCode = "alkdjabjasdsdf-53 dnalsdb..."; , startCurrent will already be at the "5" and I want to be able to extract the "53". What I have works, but it seems cumbersome... Any advice? I just noticed that my pseudo-streaming movie code causes an error with IE7. I works fine with IE8, FireFox, Chrome... I have been looking on my own and found that it's likely a misplaced comma in my code, the other browser are debugging it, but IE7 will not. The error suggests it's where I have indicated below. I've tried removing the comma just after "about_us.jpg" and that causes the script to fail completely. Can anyone help me here, please? Code: <script type="text/javascript"> //<![CDATA[ flowplayer("player", {src: "http://www.mysite.org/flowplayer/flowplayer.commercial-3.2.5.swf", wmode: 'opaque'}, { // product key from your account key: '#$xxxxxxxxx', // configure clip to use "lighthttpd" plugin for providing video data playlist: [ { url: 'http://www.mysite.org/media/video/about_us.jpg', }, //<----error suggest here??? { url: 'http://www.mysite.org/flowplayer/streamer.php?file=about_us.flv', provider: 'lighttpd', bufferLength: "2", autoBuffering: false }], // streaming plugins are configured normally under the plugins node plugins: { lighttpd: { url: 'http://www.mysite.org/flowplayer/flowplayer.pseudostreaming-3.2.5.swf', // use ${start} as a placeholder for the target keyframe queryString:escape('&start=${start}') } } }); //]]> </script> I have a function below where every time a question is submitted, it will add a new row in the table with a textbox which allows numbers entry only. My question is that I don't know how to code these features in this function: 1: I want the text box to be between 0 and 100, so if text box contains a number which is above 100, it will automatically change the number to the maximum number which is 100. Does any one know how to code this in my function below in javascript: Code: function insertQuestion(form) { var row = document.createElement("tr"); var cell, input; cell = document.createElement("td"); cell.className = "weight"; input = document.createElement("input"); input.name = "weight_" + qnum; input.onkeypress = "return isNumberKey(event)"; cell.appendChild(input); row.appendChild(cell); } What are the differences between these? 1. Code: document.domain 2. Code: window.location.hostname 3. Code: self.document.location.hostname #1 and #2 I would think are very cloes, #3 would be if someone framed the site the script was on, it would show the framed site, and not the site that is framing? because of self. I am trying to figure out how to make a random number I can plug into a script count down from that number at certain times of the day until it reaches 0. I would like it to reset itself at midnight every day. I'm trying to make it work with a script I found on here that resets itself at midnight every day. So instead of it counting down too fast, it would count down to the next number after a randomly generated number of minutes until it reaches 0. But it wouldn't necessarily have to end at 0 at midnight. It could go from 845 to 323 at the end of the day at a slower pace. Is that possible?
Hi, I wrote some javascript for a slideshow. The main webpage contains: Code: <FORM NAME="myform"> <IMG SRC="firstimage.jpg" NAME="mypic"><br> <INPUT TYPE="text" SIZE="180" NAME="mycaption" VALUE="First Caption"> <INPUT TYPE="button" VALUE="Prev" NAME="prevbutton" DISABLED=true ONCLICK="slideshowBack()"> <INPUT TYPE="button" VALUE="Next" NAME="nextbutton" ONCLICK="slideshowUp()"> </FORM> which assigns the image and caption for the first picture, and sets the Prev and Next buttons to disabled and not disabled respectively. So you start with the first image and caption, and an enabled "Next" button. I have global javascript variables: num (init to 1), max (init to 7), img1..7 (new Image ()), img1..7.src (filenames for the images), text1..7 (captions for the images), map1..7 (maps for the images). The function for moving to the next slide is: Code: function slideshowUp() { num=num+1 if (num==max+1) {num=1} document.mypic.src=eval("img"+num+".src") document.getElementById("mypic").useMap=eval("map"+num) document.myform.mycaption.value=eval("text"+num) document.getElementById("prevbutton").disabled=(num==1) document.getElementById("nextbutton").disabled=(num==max) } I developed this in HMTLPad (10.2) and it works perfectly in that program's preview mode. But it won't work in the main browsers! In IE 9 (9.0.33), when you click the Next button, nothing at all happens. Image and caption stay the same, Next stays enabled, Prev stays disabled. Maps don't work. Chrome (38.0.2125.122 m) and Firefox (27.0) behave like each other. The images change, but not the captions or the Prev/Next buttons. Maps don't work. Is this to be expected? If so, how do I work around it? Can someone explain to me the differences between the following code snippets? Mainly i don't understand the purpose of using prototype and not sure if there is a functional difference between the syntax of declaring functions. Code: var myObj = function () { this._myInt = 1; } myObj.prototype = { myNewFunction: function() { this._myInt = 2; } } VERSUS Code: var myObj = function () { this._myInt = 1; function myNewFunction(){ this._myInt = 2; } } Hi all, This is my first post of many and am new to JS. I'm familiar with Java so I shouldn't be too lost. What I'm about to do is add support for a web app from Firefox to IE that uses OpenLayers. I've searched and found a link to this site from another thread which had a list of supported functions and what not he http://www.quirksmode.org/dom/w3c_core.html From what I've read in the last hour it seems as though I will have to use some browser sniffing (isMozilla, isIE8, etc) and have multiple conditions (if-else's) in my functions to use the proper calls. Does anyone have extra material that contains differences between IE and firefox? Someone mentioned to me that in lists IE doesn't support trailing commas but ff does.. Things like this would be very helpful Thanks, Chris Greeting Everyone, Can anyone breakdown the differences between programming languages in VERY VERY BASIC plain English? (i.e. HTML use for website format, CSS used for the graphics on the webpage) Here's what I have questions about: 1. Differences between the most commonly used programming languages for software/web development (Javascript, Ruby on Rails, Phyton, etc.). 2. How do you determine which programming languages to use? 3. What factors are considered? Thank in advance for the people that reply. =) I'm trying to find the difference between 2 times. Time formats are 00:00:00.0 For example... var t1 = "00:07:51.0"; var t2 = "00:53:21.0"; How do I calculate the difference between those 2 times? TIA. I'm sure this is old news, but I am trying to use the CSS Horizonal List Menu script on JavascriptKit and having some display problems. http://www.javascriptkit.com/script/...stopmenu.shtml It works well except that I can't seem to get the CSS settings to display the same way in FF and IE. I can use pixel settings for the box size to get the menu across the entire screen in FF, but it only goes about 80% of the way in IE. If I maximize for IE, then the FF menu wraps. The % options for box size don't seem to work either. I am using Dreamweaver 4 for css settings. Is this just a limitation in the way the two browsers interpret the code? If there is an easy fix I could try it, otherwise I can live with what I have. I just need to know if there is some way to deal with it or not. If interested, the current version is at: www.chromafrica.com/template/template2.html. Hello, As a novice, I'm not sure which one to use though. I'm trying to do a calculation with numbers in JavaScript using variables, particularly adding variables. Any guided understanding of this concept is welcome. For example: Code: n = parseint(n) document.write(n += m) The following code results in the exact same output. Is there an advantage to using i++ over ++i (or visa-versa) in the loop? Code: <script type="text/javascript"> var tarr1 = []; for (var i=0; i<10; i++) { tarr1.push(i); } var tarr2 = []; for (var i=0; i<10; ++i) { tarr2.push(i); } alert(tarr1.join(',')+'\n'+tarr2.join(',')); </script> Similar question for the increment method in the following: Code: <script type="text/javascript"> var tarr1 = []; var i=0; do { tarr1.push(i); i++; } while (i<10); var tarr2 = []; var j=0; do { tarr2.push(j); ++j; } while (j<10); alert(tarr1.join(',')+'\n'+tarr2.join(',')); </script> Hey all, I have a simple example below showing how when I pass in the value of the value attribute of option node, and then use if operator to check whether parameter is a string or not, even though it's a string, it converts it to false boolean and triggers the else statement rather than calling a function: Code: <body> <select> <option value="createMsg">Add Message</option> <option value="removeMsg">Remove Message</option> </select> </body> Code: var menu = { handleMenu : function(callback){ if(callback === "string"){ menu[callback](); } else { console.log("Issue occurred") } }, createMsg : function(){ var content = document.createTextNode("Please give additional information."), heading = document.createElement("h1"); heading.appendChild(content); document.body.appendChild(heading); }, removeMsg : function(){ } } document.getElementsByTagName('select')[0].onchange = function(){ menu.handleMenu(this.value)}; callback should be a string so why is it saying otherwise? Thanks for response I am delving into the coding world and while I understand the basic principle of cookies, conditional statements, arrays, etc... I am still learning how to properly implement them. Any asistance with the following situation would be greatly appreciated and help with my learning as I try to reverse engineer the logic. I have looked around the web and this forum with little success. If the situation below is too complicated, I would really appreciate even a shove in the right direction regarding the logic. ----------------- How could I show a preset counter which counts up from a preset, beginning number toward a preset, end number? I imagine the increment and speed is set be the difference between the two numbers and a timeframe. Assumptions: I would rather not set the increment but edit the end number to show a steady increase. As I update that number, the increment adapts dynamically. I would want the number/script to be useful, so it should not refresh to the beginning number on each page load (i.e. num=0). When a visitor comes to the page, it must seem like the counter has been steadily been increasing in their absence. Coke or Pesi did something similar one time regarding cans sold to date (doubt it was plugged into a DB somewhere but rather based on a steady sales figure) and it was pretty cool. All the best! I need to write something like this: http://justsheri.com/webscripting/wsassignment/1049950/ If you look at the code there is 52 of these <img src = './images/blank1.png' onClick='clickCard("qh",0)'/> where clickcard("numchanges", increments by 1) how is this done? Thanks Danny |