I have a very stupid problem. This code:
var x=5;
console.log(x*20+x-1);
prints out 104 as expected but this:
function Go(){
x = document.getElementById("input").value;
console.log(x);
console.log(x*20+x-1);
}
prints out 5 and then 1004. Why is this?
console.log(x*20) prints 100. I tried putting brackets around it and then adding (x-1) but it still outputs 1004.
The value property of the input element is a string, so your x is actually "5"—not the number 5. What follows is JavaScript’s way of doing implicit type conversion for arithmetics:
"5" * 20 + "5" - 1
= 100 + "5" - 1
= "1005" - 1
= 1004
So in the first step, "5" is correctly converted to the number 5, leaving 100 as the intermediary result. However, adding a string to a number will convert the number into a string, so what happens next is a string concatenation to "1005". Finally, the number 1 is subtracted from the string, which causes the string to be converted to a number again, yielding the final result: 1004.
To avoid this, you can simply convert the x to a number first:
var x = document.getElementById("input").value;
x = parseInt(x, 10); // or parseFloat(x) if you’re interested in a decimals
console.log(x * 20 + x - 1);
Fun fact: If you wrote x * 21 - 1, which is equivalent to your calculation, the problem wouldn’t have appeared.
The value of an input element is a string value, so what you are getting is:
"5" * 20 = 100
100 + "5" = "1005"
"1005" - 1 = 1004
This has nothing to do with being in a function or not. Your two code snippets are not equivalent.
You can solve this by doing:
function Go(){
x = +(document.getElementById("input").value);
console.log(x);
console.log(x*20+x-1);
}
That will convert the input element value to a numeric value at the beginning.
document.getElementById("input").value returns a string. You need to convert it to and integer for it to work. So use parseInt()
function Go(){
x = parseInt(document.getElementById("input").value);
console.log(x);
console.log(x*20+x-1);
}
Related
I was wondering what the = +_ operator means in JavaScript. It looks like it does assignments.
Example:
hexbin.radius = function(_) {
if (!arguments.length)
return r;
r = +_;
dx = r * 2 * Math.sin(Math.PI / 3);
dy = r * 1.5;
return hexbin;
};
r = +_;
+ tries to cast whatever _ is to a number.
_ is only a variable name (not an operator), it could be a, foo etc.
Example:
+"1"
cast "1" to pure number 1.
var _ = "1";
var r = +_;
r is now 1, not "1".
Moreover, according to the MDN page on Arithmetic Operators:
The unary plus operator precedes its operand and evaluates to its
operand but attempts to converts it into a number, if it isn't
already. [...] It can convert string representations of integers and
floats, as well as the non-string values true, false, and null.
Integers in both decimal and hexadecimal ("0x"-prefixed) formats are
supported. Negative numbers are supported (though not for hex). If it
cannot parse a particular value, it will evaluate to NaN.
It is also noted that
unary plus is the fastest and preferred way of converting something into a number
It is not an assignment operator.
_ is just a parameter passed to the function.
hexbin.radius = function(_) {
// ^ It is passed here
// ...
};
On the next line r = +_; + infront casts that variable (_) to a number or integer value and assigns it to variable r
DO NOT CONFUSE IT WITH += operator
=+ are actually two operators = is assignment and + and _ is variable name.
like:
i = + 5;
or
j = + i;
or
i = + _;
My following codes will help you to show use of =+ to convert a string into int.
example:
y = +'5'
x = y +5
alert(x);
outputs 10
use: So here y is int 5 because of =+
otherwise:
y = '5'
x = y +5
alert(x);
outputs 55
Where as _ is a variable.
_ = + '5'
x = _ + 5
alert(x)
outputs 10
Additionally,
It would be interesting to know you could also achieve same thing with ~ (if string is int string (float will be round of to int))
y = ~~'5' // notice used two time ~
x = y + 5
alert(x);
also outputs 10
~ is bitwise NOT : Inverts the bits of its operand. I did twice for no change in magnitude.
It's not =+. In JavaScript, + means change it into number.
+'32' returns 32.
+'a' returns NaN.
So you may use isNaN() to check if it can be changed into number.
It's a sneaky one.
The important thing to understand is that the underscore character here is actually a variable name, not an operator.
The plus sign in front of that is getting the positive numerical value of underscore -- ie effectively casting the underscore variable to be an int. You could achieve the same effect with parseInt(), but the plus sign casting is likely used here because it's more concise.
And that just leaves the equals sign as just a standard variable assignment.
It's probably not deliberately written to confuse, as an experienced Javascript programmer will generally recognise underscore as a variable. But if you don't know that it is definitely very confusing. I certainly wouldn't write it like that; I'm not a fan of short meaningless variable names at the best of times -- If you want short variable names in JS code to save space, use a minifier; don't write it with short variables to start with.
= +_ will cast _ into a number.
So
var _ = "1",
r = +_;
console.log(typeof r)
would output number.
I suppose you mean r = +_;? In that case, it's conversion of the parameter to a Number. Say _ is '12.3', then +'12.3' returns 12.3. So in the quoted statement +_ is assigned to r.
_ is just a a variable name, passed as a parameter of function hexbin.radius , and + cast it into number
Let me make a exmple same like your function .
var hexbin = {},r ;
hexbin.radius = function(_) {
if (!arguments.length)
return r;
console.log( _ , typeof _ )
r = +_;
console.log( r , typeof r , isNaN(r) );
}
and run this example function .. which outputs
hexbin.radius( "1");
1 string
1 number false
hexbin.radius( 1 );
1 number
1 number false
hexbin.radius( [] );
[] object
0 number false
hexbin.radius( 'a' );
a string
NaN number true
hexbin.radius( {} );
Object {} object
NaN number true
hexbin.radius( true );
true boolean
1 number false
It Will assign new value to left side variable a number.
var a=10;
var b="asg";
var c=+a;//return 10
var d=-a;//return -10
var f="10";
var e=+b;
var g=-f;
console.log(e);//NAN
console.log(g);//-10
Simply put, +_ is equivalent to using the Number() constructor.
In fact, it even works on dates:
var d = new Date('03/27/2014');
console.log(Number(d)) // returns 1395903600000
console.log(+d) // returns 1395903600000
DEMO:
http://jsfiddle.net/dirtyd77/GCLjd/
More information can also be found on MDN - Unary plus (+) section:
The unary plus operator precedes its operand and evaluates to its operand but attempts to converts it into a number, if it isn't already. Although unary negation (-) also can convert non-numbers, unary plus is the fastest and preferred way of converting something into a number, because it does not perform any other operations on the number. It can convert string representations of integers and floats, as well as the non-string values true, false, and null. Integers in both decimal and hexadecimal ("0x"-prefixed) formats are supported. Negative numbers are supported (though not for hex). If it cannot parse a particular value, it will evaluate to NaN.
+_ is almost equivalent of parseFloat(_) . Observe that parseInt will stop at non numeric character such as dot, whereas parshFloat will not.
EXP:
parseFloat(2.4) = 2.4
vs
parseInt(2.4) = 2
vs
+"2.4" = 2.4
Exp:
var _ = "3";
_ = +_;
console.log(_); // will show an integer 3
Very few differences:
Empty string "" evaluates to a 0, while parseInt() evaluates to NaN
For more info look here: parseInt vs unary plus - when to use which
In this expression:
r = +_;
'+' acts here as an unary operator that tries to convert the value of the right operand. It doesn't convert the operand but the evaluated value. So _ will stay "1" if it was so originally but the r will become pure number.
Consider these cases whether one wants to apply the + for numeric conversion
+"-0" // 0, not -0
+"1" //1
+"-1" // -1
+"" // 0, in JS "" is converted to 0
+null // 0, in JS null is converted to 0
+undefined // NaN
+"yack!" // NaN
+"NaN" //NaN
+"3.14" // 3.14
var _ = "1"; +_;_ // "1"
var _ = "1"; +_;!!_ //true
var _ = "0"; +_;!!_ //true
var _ = null; +_;!!_ //false
Though, it's the fastest numeric converter I'd hardly recommend one to overuse it if make use of at all. parseInt/parseFloat are good more readable alternatives.
Hello Stackoverflow people,
My question is how to change a variable I assigned with JavaScript using the value of an HTML input tag.
my progress:
<script type="text/javascript">
var x = 0;
document.write(x);
function addtox() {
var addx = document.getElementById("plusx").value;
x = x + addx;
}
</script>
<input id="plusx" type="number">
<input type="button" onclick="addtox()" value="add">
The result is that it literally adds the value of id="plusx" to the 0 that's already there. So if the input would be 50, it would return 050, and not 50. If I repeat the button it returns 05050 in stead of 100.
How can I fix this?
Also: how can I update text that is already writting to the screen? x is already written to the screenbefore the change and doesn't update after it is assigned a new value.
p.s
Sorry if I am a bit vague, not too familiar with coding questions like mine.
The value of an input element is a string type. You need to convert it to an integer:
x += parseInt(document.getElementById("plusx"), 10);
The return value from dom lookup is string. And so the result you are getting is string concatenation. Convert the return from dom lookup to integer using the parseInt () function. Then you should get the correct answer.
You can just put
X = "0" + addx;
This way you will always have the 0
- this will work if you just want to place a 0 In front.
if you want a more simple way of converting to integer just times your value by 1 will convert the strings to numbers.
So add in x = 0 * 1
And x= x + addx * 1
This will just give you your result without a 0 in front.
If you want 0 in front and number do
X = "0" + addx * 1;
While I do know that the following question is stupid simple, it is related to a specific situation that I have been unable to find through Google. The following code is in Javascript.
Suppose there is a variable
x = x + 1;
I can see from a tutorial that this is supposed to work. However, how are we supposed to use this variable in a calculation?
I have tried with the following codes
var name = name + 1;
alert(name);
The above outputs "NaN"; whatever that is...
var name = name + 1;
name = 2;
alert(name);
The above outputs 2 which is simply overriding the original variable.
name = prompt("input any number");
var name = name + 1
alert(name);
The above outputs the input provided + 1 as a string, i.e. 01 where the input is "0" without quotes.
I remember from a ruby lesson that we use .to_i in order to convert a string to an integer. How do we go about doing this in Javascript?
var name = name + 1;
The above code declares a new variable called name which contains whatever name contained before, plus 1. Since name only just came into existence, it doesn't have a numeric value ("Not A Number", or NaN). Adding 1 to NaN gives NaN.
+ means different things in different contexts. If the two operands are numbers, then it does addition. If one operand is a String, it does String concatenation, so
var x = "2"; // x is the String "2"
alert(x+2); // "22"
var x = 2; // x is the number 2
alert(x+2); // 4
If you want to convert a String to a number, you can do
if (x) x = parseInt(x, 10);
where the second argument is the radix (i.e. the base of the number system), and you should use it. If someone entered 02 for example, the radix prevents javascript from treating that as an octal (or other) number.
Of course, you always need to make sure your variables are defined before you use them. I bet your NaN result is coming from the variable not being defined.
Your issue is that you never initialize name. For example:
var name = 0;
alert(name); // Name is 0
name = name + 1;
alert(name); // Name is 1
If you don't initialize it, it will give you NaN: Not a Number.
To turn a string into a number, use parseInt or parseFloat:
var name = prompt("input any number"); // I input 3
name = parseFloat(name);
name = name + 1;
alert(name); // Name is 4
Use parseInt to convert a string to a number.
The line x = x + 1 says "take the existing value of x, add one to it, and store the resulting value back in x again".
The line var name = name + 1 is meaningless since name does not have an existing value when the statement is executed. It is the same as saying undefined + 1 which is NaN (Not a Number).
Here are some examples of how the + operator works in JavaScript:
1 + 2 // number + number is a number -> 3
"1" + 2 // string + anything is a string => "12"
1 + "2" // anything + string is a string => "12"
"1" + "2" // string + string is a string => "12"
NaN means "not a number". Since name has no value when it is first declared, saying "var name = name + 1" doesn't have a numerical meaning, since name is in the process of being declared when used for the first time.
In the second example, name is determined to be a string. Javascript isn't as sensitive to types as some other languages, so it uses + as a concatenation operator instead of a numerical one, since it makes more sense in context,
I have this below loop in my function
I see it loop through if x is <10 but if it is greater than 10 it fails even though the condition of y < x satisfies
function insert(x,y) {
for (var shift = y; shift < x; shift++) {
//get into loop for insert (9,2) but not for insert(10,2)
}
}
This is the actual function, I am trying to visualize a insert before scenario using rapheal.js it works for insertBeforeTo(9,2) but when i try insertBeforeTo(10,2) it do not get into the loop.
function insertBeforeTo(whichElementI, insertBeforeI) {
var twhichElement = blocks[whichElementI];
blocks[whichElementI].animate({ x: blocks[insertBeforeI].attr('x') }, 1000, ">");
var shiftplusone = insertBeforeI;
for (var shift = insertBeforeI; shift < whichElementI; shift++) {
++shiftplusone;
blocks[shift].animate({ x: blocks[shiftplusone].attr('x') }, 1000, ">");// check value actually changes
}
}
Down voters: mind explaining?
Issue found: while debugging I see whichElementI and insertBeforeI values in ' '. So I assume It takes it as a string and as nnnnn and paxdiablo rightly pointed out, it takes as string instead of int so It worked for whichElementI = 9 and insertBeforeI = 2 and not whichElementI= 10 ,insertBeforeI=2.
So I used unary plus operator like +whichElementI, +insertBeforeI which fixes the issue.
Thanks
I'm guessing you are inadvertantly calling your function with string values rather than number values, that is with
insert("9", "2")
insert("10", "2")
...rather than
insert(9, 2)
insert(10, 2)
If you are getting your values from html element attributes, for example, they'll be strings.
With strings, "2" < "9" is true, but "2" < "10" is false - it does a lexicographic (dictionary) order comparison, not a numeric comparison.
If you want your function to work either way then you can change it to convert strings to numbers (I prefer to use the unary plus operator for that purpose):
function insert(x,y) {
x = +x;
y = +y;
for (var shift = y; shift < x; shift++) {
//get into loop for insert (9,2) but not for insert(10,2)
}
}
I don't know what the types of whichElementI and insertBeforeI are, but convert them to numeric by *1. That should help keep some of the arithmetic in check. Might also want to check if(isNaN(some_var)==false){...} as a sanity check.
function insertBeforeTo(whichElementI, insertBeforeI) {
var twhichElement = blocks[whichElementI];
blocks[whichElementI].animate({ x: blocks[insertBeforeI].attr('x') }, 1000, ">");
var shiftplusone = insertBeforeI*1;
for (var shift = insertBeforeI*1; shift < whichElementI*1; shift++) {
++shiftplusone;
blocks[shift].animate({ x: blocks[shiftplusone].attr('x') }, 1000, ">");// check x value actually changes
}
}
You should first check what data types you're passing in to the function.
For example, all of these produce output:
insert ( 10, 2)
insert ( 9, 2)
insert ( '9', '2')
but the following does not:
insert ( '10', '2')
That's because the string '10' is actually less than the string '2'. By that, I mean that a string is not treated numerically when sorting or comparing, rather each character is compared individually, leading to things like the first twelve numbers being sequenced as:
1
10
11
12
2
3
4
5
6
7
8
9
You can see this in action with the following code (at one of the many on-line JS runners):
function insert(x,y) {
for (var shift = y; shift < x; shift++) {
//get into loop for insert (9,2) but not for insert(10,2)
document.write('x');
}
}
document.write('<br>10,2 as string: '); insert ('10','2');
document.write('<br>9,2 as string: '); insert ( '9','2');
document.write('<br>9,2 as num: '); insert ( 9, 2);
document.write('<br>10,2 as num: '); insert ( 10, 2);
which outputs:
10,2 as string:
9,2 as string: xxxxxxx
9,2 as num: xxxxxxx
10,2 as num: xxxxxxxx
If you have a string that you want treated as a number, parseInt() is one way to go, something like:
var str42 = '42';
var num42 = parseInt (str42, 10);
var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
var resstr=result.toString();
var res=resstr.split(".");
var test=parseInt(res[1].charAt(0));
var test1=parseInt(res[1].charAt(1));
this is my code when my value in res variable is 5.90 then I alert test & test1 variable
in test alert it shows correct value i.e. "9" but in test1 alert it shows message like "Nan"
if res variable contain value 5.35 then it work correct i.e.test=3 & test1=5
only it does not work when test1 contains value "0" it gives message "Nan"
The problem is that you create a string such as '12.3', and split it to 3. .charAt(1) on that string returns an empty string, '', which parseInt turns into a NaN.
Well, an easy and hacky fix would be:
test1 = test1 || 0;
You may also consider a calculation instead of string manipulation:
var result = 98.1234;
var d1 = Math.floor(result * 10) % 10;
var d2 = Math.floor(result * 100) % 10;