Why when I use this: (assuming i = 1)
divID = "question-" + i+1;
I get question-11 and not question-2?
Use this instead:
var divID = "question-" + (i+1)
It's a fairly common problem and doesn't just happen in JavaScript. The idea is that + can represent both concatenation and addition.
Since the + operator will be handled left-to-right the decisions in your code look like this:
"question-" + i: since "question-" is a string, we'll do concatenation, resulting in "question-1"
"question-1" + 1: since "queston-1" is a string, we'll do concatenation, resulting in "question-11".
With "question-" + (i+1) it's different:
since the (i+1) is in parenthesis, its value must be calculated before the first + can be applied:
i is numeric, 1 is numeric, so we'll do addition, resulting in 2
"question-" + 2: since "question-" is a string, we'll do concatenation, resulting in "question-2".
You may also use this
divID = "question-" + (i*1+1);
to be sure that i is converted to integer.
Use only:
divID = "question-" + parseInt(i) + 1;
When "n" comes from html input field or is declared as string, you need to use explicit conversion.
var n = "1"; //type is string
var frstCol = 5;
lstCol = frstCol + parseInt(n);
If "n" is integer, don't need conversion.
n = 1; //type is int
var frstCol = 5, lstCol = frstCol + n;
Since you are concatenating numbers on to a string, the whole thing is treated as a string. When you want to add numbers together, you either need to do it separately and assign it to a var and use that var, like this:
i = i + 1;
divID = "question-" + i;
Or you need to specify the number addition like this:
divID = "question-" + Number(i+1);
EDIT
I should have added this long ago, but based on the comments, this works as well:
divID = "question-" + (i+1);
divID = "question-" + parseInt(i+1,10);
check it here, it's a JSFiddle
Another alternative could be using:
divID = "question-" + (i - -1);
Subtracting a negative is the same as adding, and a minus cannot be used for concatenation
Edit: Forgot that brackets are still necessary since code is read from left to right.
Add brackets
divID = "question-" + (i+1);
using braces surrounding the numbers will treat as addition instead of concat.
divID = "question-" + (i+1)
The reason you get that is the order of precendence of the operators, and the fact that + is used to both concatenate strings as well as perform numeric addition.
In your case, the concatenation of "question-" and i is happening first giving the string "question=1". Then another string concatenation with "1" giving "question-11".
You just simply need to give the interpreter a hint as to what order of prec endence you want.
divID = "question-" + (i+1);
Joachim Sauer's answer will work in scenarios like this. But there are some instances where adding parentheses won’t help.
For example: You are passing “sum of value of an input element and an integer” as an argument to a function.
arg1 = $("#elemId").val(); // value is treated as string
arg2 = 1;
someFuntion(arg1 + arg2); // and so the values are merged here
someFuntion((arg1 + arg2)); // and here
You can make it work by using Number()
arg1 = Number($("#elemId").val());
arg2 = 1;
someFuntion(arg1 + arg2);
or
arg1 = $("#elemId").val();
arg2 = 1;
someFuntion(Number(arg1) + arg2);
var divID = "question-" + (parseInt(i)+1);
Use this + operator behave as concat that's why it showing 11.
Care must be taken that i is an integer type of variable. In javaScript we don't specify the datatype during declaration of variables, but our initialisation can guarantee that our variable is of a specific datatype.
It is a good practice to initialize variables of declaration:
In case of integers, var num = 0;
In case of strings, var str = "";
Even if your i variable is integer, + operator can perform concatenation instead of addition.
In your problem's case, you have supposed that i = 1, in order to get 2 in addition with 1 try using (i-1+2). Use of ()-parenthesis will not be necessary.
- (minus operator) cannot be misunderstood and you will not get unexpected result/s.
One place the parentheses suggestion fails is if say both numbers are HTML input variables.
Say a and b are variables and one receives their values as follows (I am no HTML expert but my son ran into this and there was no parentheses solution i.e.
HTML inputs were intended numerical values for variables a and b, so say the inputs were 2 and 3.
Following gave string concatenation outputs: a+b displayed 23; +a+b displayed 23; (a)+(b) displayed 23;
From suggestions above we tried successfully : Number(a)+Number(b) displayed 5; parseInt(a) + parseInt(b) displayed 5.
Thanks for the help just an FYI - was very confusing and I his Dad got yelled at 'that is was Blogger.com's fault" - no it's a feature of HTML input default combined with the 'addition' operator, when they occur together, the default left-justified interpretation of all and any input variable is that of a string, and hence the addition operator acts naturally in its dual / parallel role now as a concatenation operator since as you folks explained above it is left-justification type of interpretation protocol in Java and Java script thereafter. Very interesting fact. You folks offered up the solution, I am adding the detail for others who run into this.
Simple as easy ... every input type if not defined in HTML is considered as string. Because of this the Plus "+" operator is concatenating.
Use parseInt(i) than the value of "i" will be casted to Integer.
Than the "+" operator will work like addition.
In your case do this :-
divID = "question-" + parseInt(i)+1;
Related
I'm creating totals for a row in a table with JavaScript. The cell values are typed as strings, so a += would concatenate a delta. Is there anything that lets me cast this value in one line, so I can still use += without saving the old value in a old = Number(value) in an extra lin of code?
row.totals.value += delta;
[string] [Integer]
I'm not certain you can +=, but you should be able to use this on one line:
row.totals.value = Number(rows.totals.value) + delta;
You can do it in the following way
let str = '123';
str = +str + 4;
console.log(str);
Unfortunately it won't be possible to do it without a casting of the LHS in conjunction with +=.
You'd also probably want to be using parseInt() or parseFloat() rather than Number(). Further reading.
An interesting thing I've never seen before was posted in another question. They had something like:
var i = + +1;
They thought the extra + converted it to a string, but they were simply adding to a string which is what caused it to convert.
This, however, lead me to the question: what is going on here?
I would have actually expected that to be a compiler error, but JavaScript (at least in Chrome) is just fine with it... it just basically does nothing.
I created a little JSFiddle to demonstrate: Demo
var i = 5;
var j = + +i;
document.body.innerHTML = i === j ? 'Same' : 'Different';
Anyone know what's actually occurring and what JavaScript is doing with this process?
I thought maybe it would treat it like ++i, but i doesn't increment, and you can even do it with a value (e.g., + +5), which you can't do with ++ (e.g., ++5 is a reference error).
Spacing also doesn't affect it (e.g., + + 1 and + +1 are the same).
My best guess is it's essentially treating them as positive/negative signs and putting them together. It looks like 1 == - -1 and -1 == + -1, but that is just so weird.
Is this just a quirky behavior, or is it documented in a standard somewhere?
Putting your the statement through the AST Explorer, we can see that what we get here is two nested Unary Expressions, with the unary + operator.
It's a unary expression consisting of + and +i, and +i is itself a unary expression consisting of + and i.
The unary expression with the unary + operator, will convert the expression portion into a number. So you're essentially converting i to a number, then converting the result of that to a number, again (which is a no-op).
For the sake of completion, it works on as many levels as you add:
var i = 5;
console.log(+ + + + + +i); // 5
console.log(i); // still 5
It's in the specification.
Digging through, we can see from §14.6.2.2 that the increment and decrement operators are listed before (and should be preferred) over the unary operators. So precedence alone won't explain this.
Looking up the the punctuation table in §11.7, we can see that every single instance of ++ (the operator) in the spec shows the two together, without whitespace. That's not conclusive, until you check...
The whitespace rules in §11.2, specifically:
White space code points may occur within a StringLiteral, a RegularExpressionLiteral, a Template, or a TemplateSubstitutionTail where they are considered significant code points forming part of a literal value. They may also occur within a Comment, but cannot appear within any other kind of token.
JS does not allow arbitrary whitespace mid-operator.
The JS syntax in both PegJS and Esprima corroborate this, matching on the literal two-character string ++.
For me it's very clear;
var a = +3;
var b = +a; // same as a, could be -a, for instance
var c = + +a; // same as above, same as +(+a)
If you do ++variable the javascript interpreter sees it as the increment operator.
If you do + +variable the javascript interpreter sees it as Unary plus, coercing the value to a number, twice.
So
var a = 1;
var b = +a;
var c = +b;
console.log(c);// still 1
is the same as
var c = + +1;
So the simple answer is that two plus signs can not be separated by a space to be interpreted as incrementation, the space makes it so the interpreter sees two seperate spaces, which is what it really is
The + operators converts into a number, two + operators with a space in between does nothing additional.
Even though it might look very similar, + + and ++ are not at all the same thing for an AST interpreter. The same applies to token separation: varfoo is not the same as var foo.
In the expression + + +i, each + is considered as distinct unary operator, which simply convert your variable to a number. For the incrementation operation, which is ++, no spaces are allowed, neither between the + and the variable token. In the example below, the last line is not valid:
var x = "4";
console.log(+ + +x);
console.log(+ + ++x);
console.log(+ ++ +x);
I have a simple question to ask, in which I am slightly embarrassed to ask, but I realize that I won't learn unless I ask.
When looking at reversing a string, I recognize that reversing a string requires you to split up the string, reverse it, and then re-join it. Like so.
var stringReverse = function (n){
return n.split("").reverse().join("");
}
console.log(stringReverse("hello"));
However, I was trying to reverse a number, much of the principles were very similar except for one part. The code below is:
var reverse_a_number = function (n){
n = n + "";
return n.split("").reverse().join("");
}
console.log(reverse_a_number(32243));
My question is why am I needed to bring in the " n = n + " ";" to the code? I was assuming that the same principles would be similar regardless of it being a string, or an integer.
Much thanks in advance, and I apologize that this question is elementary.
why am I needed to bring in the " n = n + " ";" to the code?
Adding + "" will make a cast to String, this way you can use String functions (.split).
The integer have only functionality of a Number. If you want to treat the Number as a String you need to cast it (+ "") or convert it (.toString())
The .reverse() function come from Array object that is created when you use String function .split().
With .join() you come back to String from Array (of characters).
If you want to come back to Number after reverting, you can choose one of these functions.
To put it simply, the docs require it to be a string. You could combine your two methods by doing exactly what you're doing in reverse_a_number (it works for both). Also, don't be embarrassed to ask questions, it's how you learn :)
Number doesn't have reverse and split method directly and you should convert number to string that be able reverse it.
to convert it you can add an empty string after it, like you.
just it.
Javascript sets the type of a variable at runtime.
If she (yes, it's a girl) sees that you only have ciphers, she will consider it's an integer.
Adding + ""; casts it into a string, which is an array of chars.
Your string is stored a lil bit like : ['h', 'e', 'l', 'l', 'o']
an integer is stored as {0011001010101...}
Explanation
You are passing in a number, not a string. When you combine a number with a string ("") it assumes you want to make a string. So you are really converting it to a string. To an array, then back to a string. If you attempt to split a number, the compiler will throw an error. More exactly
TypeError: undefined is not a function (evaluating 'n.split('')')
So what you really are doing is making the number into a String. There are different methods you can use, take a look here.
n += '';(String) ->
.split() (Array) -> .split() (Array) -> .join() (String)
Your function is actually producing and returning a string
Alternative Function
I'm going to critique ;) , you could shorten, and improve this function using the following.
var reverse_a_number = function (n){
return +(n += "").split("").reverse().join("");
}
What does this do?
n = n + '' has a special operator, +=. We can shorten this to on-line by using this inside parenthesis. The + will convert it into a Integer
A number doesn't have the split method. You have to convert it into a string, which does have split.
You can use typeof to find out the type of a variable. The following code snippet demonstrates the types of a number and a string, and shows the value of the split attribute for each one. Note that split is undefined for the number.
var n = 42;
document.write(typeof n, '<br />', n.split, '<br />', '<br />');
var s = ''+n;
document.write(typeof s, '<br />', s.split);
If you want to reverse an integer by treating it as an integer, without using string operations, you can do the following.
function reverseInteger(n) {
var result = 0;
while (n != 0) {
var digit = n%10;
result = 10*result + digit;
n = (n-digit)/10;
}
return result;
}
var n = 3141590123456;
document.write(n, '<br />');
document.write(reverseInteger(n));
Note that the last digit of n is n%10. If we subtract the last digit and divide n by ten, the effect is to shift n one digit to the right. We keep doing this and build up result in reverse by multiplying it by ten on each iteration and adding the digit that we just removed from n.
When I run my script rather than adding what I think should be two numbers, it concatenates...
I feel like I'm watching that Abbot and Costello bit. https://www.youtube.com/watch?v=9o1SAS8KyMs
var weekNum = e.parameter.weekListBox;
weekNum = weekNum + 3;
weekListBox has the values from 1 to 15.
I am trying to offset it by 3.
However 1 + 3 yields 13, not 4 as I was expecting. Drove me nuts till I realized why this was happening.
So how do I get it to add?
Thanks
It turns out, this is the only solution that worked for me... Very strange problem.
Google Spreadsheet Script getValues - Force int instead of string
Answered by hoogamaphone
You can do this easily using the unary '+' operator as follows:
First get your values from your spreadsheet using getValue() or
getValues(). Suppose you get two such values, and store them in A = 1
and B = 2. You can force them to be recognized as numbers by using any
math binary operator except for +, which concatenates strings, so A -
B = -1, while A + B will return '12'.
You can force the variables to be numbers simply by using the + unary
operator with any variable that might be interpreted as a string. For
example, +A + +B will return the correct value of 3.
The answer above explains the issue but does not provide a solution (except in comments but parseInt() is not the only/best solution).
The reason you have that issue is that the value returned by e.parameter.weekListBox; is actually a string (it is actually always the case except for dates which are date objects) so the result you get is the normal string concatenation (string+number=new string).
One simple solution is to change your code as follows :
var weekNum = Number(e.parameter.weekListBox);// make it a number
weekNum = weekNum + 3;// and the result will be a sum
See
function myFunction() {
var aa = 1;
var ab = aa + 3;
var ba = "1";
var bb = ba + 3;
}
ab = 4
but
bb = "13"
I am trying this:
function add_things() {
var first = '2';
var second = '4';
alert(first + second);
}
But it gives me 24 instead of 6, what am I doing wrong?
You're concatenating two strings with the + operator. Try either:
function add_things() {
var first = 2;
var second = 4;
alert(first + second);
}
or
function add_things() {
var first = '2';
var second = '4';
alert(parseInt(first, 10) + parseInt(second, 10));
}
or
function add_things() {
var first = '2';
var second = '4';
alert(Number(first) + Number(second));
}
Note: the second is only really appropriate if you're getting strings from say a property or user input. If they're constants you're defining and you want to add them then define them as integers (as in the first example).
Also, as pointed out, octal is evil. parseInt('010') will actually come out as the number 8 (10 in octal is 8), hence specifying the radix of 10 is a good idea.
Try this:
function add_things() {
var first = 2;
var second = 4;
alert(first + second);
}
Note that I've removed the single quotes; first and second are now integers. In your original, they are strings (text).
That is one of the "Bad Parts" of JavaScript, as a loosely typed language, the addition and concatenation operator is overloaded.
JavaScript is loosely typed, but that doesn't mean that it has no data types just because a value of a variable, object properties, functions or parameters don't need to have a particular type of value assigned to it.
Basically there are three primitive data types:
boolean
number
string
null and undefined are two special cases, everything else are just variations of the object type.
JavaScript type-converts values of types into a type suitable for the context of their use (type coercion).
In your example were trying to add two objects of type string, so a concatenation occur.
You can "cast" or type convert the variables to number in many ways to avoid this problem:
var a = "2";
var b = "4";
// a and b are strings!
var sum = Number(a) + Number(b); // Number constructor.
sum = +a + +b; // Unary plus.
sum = parseInt(a, 10) + parseInt(b, 10); // parseInt.
sum = parseFloat(a) + parseFloat(b); // parseFloat.
This is I think a very common mistake, for example when reading user input from form elements, the value property of form controls is string, even if the character sequence that it contain represents a number (as in your example).
The "Bad Part" which I talk, is about the dual functionality of the + operator, overloaded to be used for both, numeric addition and string concatenation.
The operation that the + operator will do is determined completely by the context. Only if the both operands are numbers, the + operator perform addition, otherwise it will convert all of its operands to string and do concatenation.
The single quotes cause the values to be treated as characters instead of numbers. '2' + '4' = '24' in the same way that 'snarf' + 'blam' = 'snarfblam'.
You could also force the interpreter to perform arithmetic when dealing with numbers in string forms by multiplying the string by 1 (since multiplication can't be done on a string, it'll convert to a number if it can):
// fun with Javascript...
alert(first * 1 + second * 1);
But it's probably best to go with CMS's suggestion of using Number() to force the conversion, since someone will probably come along later and optimize the expression by removing the 'apparently unnecessary' multiply-by-one operations.