- 1
JS challenge. I do not understand the output
The output here is 1. I can not understand why. var x = 0; var a = [3, 4]; a[x] = ++x; document.write(a[0]); Does this mean that if x = 0, then a[x] is the first element of array and after ++x it becomes the second element of array with index 1? My first answer was 4.
8 Respuestas
+ 2
The ++x is the incrementation of the variable x, which is 0 right now. What ++ means before a variable is essentially:
1) Add 1 to the value of the variable.
2) Then use the value of the variable after it is incremented.
So a[x] = ++x means to increment the value of x first (to 1), then to use it in the statement, so now a[0] (x before the increment) is 1.
+ 2
plz don't confuse
your assign the value for x=0;
let me explain your code:
your code is
var x= 0;
var a= [3,4];
a[x]=++x; in this line you changed the value of array of index 0
a[x]=++x.
a[0]= 1;
you changed the value of array index 0 beacuse the value of x 0
now ,if you have any confusion the let me know
+ 1
++x is pre-incremnt the value of variable change on echo
example for u
if var = 1; if u print ++x
it returns the value of x 2 because this change the value of variable before print
+ 1
I understand how increment works. But this array a = [3,4] confuses me. I thought that after increment index 0 becomes 1 thus 4, which has index 1 should be outputed.
+ 1
Thank you, guys, for your help and time.
+ 1
Code reads like text, so when the code runs, it uses the value of x first (which is 0), and then changes the values.
+ 1
Oh, now I got it! Thank you again.
+ 1
welcome