var s= new Date().getHours(); // 20
var m= new Date().getMinutes(); // 38
document.write(s,m); // returns 2038
var time = s,m;
document.write(time); // returns only 20
var time = s+m;
document.write(time); // returns 58
How can I declare a time variable which returns 2038 using s and m variables ?
Cast one to a string.
var time = ''+s+m;
document.write(time);
You have to make sure js knows its a string first.
var time = "" + s + m;
The longer answer is that JavaScript applies some rules when it sees code like this.
In this case document.write(s,m) is just outputting each value:
var s= new Date().getHours(); // 20
var m= new Date().getMinutes(); // 38
document.write(s,m); // returns 2038
The following is declaring two variables (separated by a comma), one called time and one called m, and the value contained in variable s is being assigned to time. With JavaScript scoping rules, you can declare e.g. var m as often as you like in a function and it will always refer to the same variable m:
var time = s,m;
document.write(time); // returns only 20
JavaScript uses + for both addition and concatenation, and will try to coerce variables to match the type of the first variable in order to decide whether it is to perform addition or concatenation. In this case s is a number so it will try to perform addition on the two values:
var time = s+m;
document.write(time); // returns 58
The correct JavaScript idiom for this is to put an empty string at the beginning of the expression and JavaScript will attempt to coerce subsequent variables to that type:
var time = '' + s + m;
document.write(time); // returns 2038
Related
Before I used to construct a Number to perform operations like:
let a = 0, b = "6";
a += new Number(b); // otherwise with
a += b; // a string is created instead
But later on I've found that I can simply use the unary + (+b instead of new Number(b)).
Also Number is their own type so things like:
for(const a of new Array(new Number("3")).keys())
console.log(a)
Doesn't even work properly - the above for loop will only print out zero once.
So what could be the situations in which constructing a Number object is the only choice?
I'm really new to Javascript and trying to create a form where I'm running into some trouble...
When I use + it does not add up to the value, instead it just puts it back to back. Ex: 5+10 (510)
Here's my code if you want to take a look at it. I'd appreciate any help since I can't figure this out on my own.
var service = document.getElementById("service");
var serviceprice = service.options[service.selectedIndex].id;
var tech = document.getElementById("tech");
var techprice = tech.options[tech.selectedIndex].id;
var hours = document.getElementById("hours").value;
// The error happens here
var total = techprice * hours + serviceprice;
I also have an html part which the script gets the data from.
That happens whenever you have a string rather than a number. The + operator performs concatenation for strings. Make sure you parse your strings to numbers using parseFloat or parseInt:
var service = document.getElementById("service");
var serviceprice = parseInt(service.options[service.selectedIndex].id, 10);
var tech = document.getElementById("tech");
var techprice = parseInt(tech.options[tech.selectedIndex].id, 10);
var hours = parseInt(document.getElementById("hours").value, 10);
Note that parseInt takes an argument to specify the base. You almost always want base 10.
Try changing this line:
var total = techprice * hours + serviceprice;
to
var total = techprice * hours + parseFloat(serviceprice);
I suspect 'servicePrice' is a string, and it will then try to concatenate the first value (let's say: 100) with the second value (which is, not a number, but a string, let's say 'test'), the result being '100test'.
Try to convert the string to int first with parseInt or to float with parseFloat
This is not especially elegant, but I find it simple, easy, and useful:
var total = -(-techprice * hours - serviceprice);
or even:
var total = techprice * hours -(-serviceprice);
They both eliminate the ambiguous + operator.
I am trying to add numbers as strings using basic math. I first set the local storage to "0" then add "1" to it each time. I feel I am on the right path, but when I run this my result is not 0 + 1 = 1 rather I get "01" in my local storage. I want to be able to add 1 to the existing local storage each time so 0 + 1 I get 1. Next time around 1 + 1 I get 2, and 2 + 1 I get 3 and so on.
// sets "points" to 0 when user first loads page.
if (localStorage.getItem("points") === null){
localStorage.setItem("points", "0");
}
// get points
var totalPoints = localStorage.getItem("points");
// add 1 points to exisiting total
var addPoint = totalPoints +"1";
// set new total
localStorage.setItem("points", addPoint);
You can convert a string to a number in several ways (not an exhaustive list):
var n = s * 1; // s is the string
var n = s - 0;
var n = parseFloat(s);
var n = Number(s);
var n = ~~s; // force to 32-bit integer
var n = parseInt(s, 10); // also integer, precise up to 53 bits
Convert your strings to numbers when you fetch them from local storage, do the math, and then put the results back.
edit — the thing to keep in mind is that + is more "interesting" than the other arithmetic operators because it has meaning for string-valued operands. In fact, JavaScript tends to prefer string interpretation of the + operator, so if there's a string on one side and a number on the other, the operation is string concatenation and not arithmetic addition.
I like to add (+1) to a number. But problem is my number can sometimes have 0 preceding it. Like 01, 02, 03, 04. So I like result to be:
mockup01 + 1 = mockup02
mockup11 + 1 = mockup12
How can that be achieved? Example of how I would use it would be if I had filename named mockup_01.htm and change it to mockup_02.htm
Thanks!
Maybe this
next = (parseInt(number, 10) + 101).toString().substr(1)
to make a mockup_02.htm out of mockup_01 try this
newName = fileName.replace(/\d+(?=\.)/, function(n) {
return (parseInt(n, 10) + Math.pow(10, n.length) + 1).toString().substr(1)
});
this works with numbers of any length, e.g. mockup_0001, mockup_000001 etc
I'm not a javascript programmer, but it seems like you're mixing up presentation and internal representation. If the "01" is a string, with a corresponding integer variable, you can convert from the string to the integer, add 1, and then make a new string with the desired formatting. This is sometimes referred to as a model-view-controller pattern. The model is the integer variable - it models the internal behavior of numbers. The view is the string - it presents the number in a human readable fashion. The controller handles the numerical operations.
function next_id(input) {
var output = parseInt(input, 10)+1; // parse and increment
output += ""; // convert to string
while (output.length<2) output = "0"+output; // prepend leading zeros
return output;
}
var id = "00";
for (var i=0; i<20; i++) {
console.log(id);
id = next_id(id);
}
I am trying to use jQuery to break right ascension and declination data into their constituents (hours, minutes, and seconds) and (degrees, arc-minutes, and arc-seconds), respectively from a string and store them in variables as numbers. For example:
$dec = "-35:48:00" -> $dec_d = -35, $dec_m = 48, $dec_s = 00
Actually, the data resides in a cell (with a particular class ('ra')) in a table.
At present, I have gotten this far:
var $dec = $(this).find(".ra").html();
This gives me the declination as a string but I cannot figure out how to parse that string.
I figured out the regular expression (-|)+\d+ (this gives me -35 from -35:48:00) to get the first part. How do I use that in conjunction with my code above?
This should do it:
var dec = '-35:48:00';
var parts = dec.split(':');
parts[0] would then be -35, parts[1] would be 48, and parts[2] would be 00
You could run them all through parseInt(parts[x], 0) if you want integers out of the strings:
var dec_d = parseInt(parts[0], 10);
var dec_m = parseInt(parts[1], 10);
var dec_s = parseInt(parts[2], 10);
I should point out this really has nothing to do with jQuery and is a Javascript problem (past getting the values out of the HTML document, at least) - The practice of prefixing a variable with a $ is usually done to signify that the variable contains a jQuery collection. Since in this situation it contains HTML, it is a little misleading
Use String.match()
$dec = "-35:48:00";
matches = $dec.match(/-*[0-9]+/g);
for (i=0;i<matches.length;i++){
alert(matches[i]);
}