Sunday, June 2, 2024
 Popular · Latest · Hot · Upcoming
150
rated 0 times [  151] [ 1]  / answers: 1 / hits: 155786  / 13 Years ago, wed, may 11, 2011, 12:00:00

Why when I use this: (assuming i = 1)



divID = question- + i+1;


I get question-11 and not question-2?


More From » math

 Answers
8

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.


[#92295] Monday, May 9, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
lesterluiss

Total Points: 513
Total Questions: 104
Total Answers: 106

Location: Honduras
Member since Sat, Jul 24, 2021
3 Years ago
;