Javascript: Basic for loop? -


i completed form of competency exam programming school, , got every question correct except this, although appears quite easy, yet couldn't it. ideas?

observe code below.

var x = [1,5,7,13]; for(i=0; < x.length; i++) { x[i] = x[3-i] + 2; } 

once program done, in x?

a [3,7,9,15] b [15,9,11,3] c [15,9,7,3] d [15,9,11,17] 

the key here you're updating same array you're reading go through it. (note: i'd consider bad practice , i've seen lot of programmers fall trap - it's easy misunderstand code).

first thing realize x[3-i] reads opposite end of current index. more generic, should have been x[(x.length-1)-i] 3 hardcoded in case.

now, first round easy: 13+2 = 15. 13 because opposite end of first element last element:

x = [15,5,7,13]       ▲      │ this+2       └──────┘  

in second round replace 5 7+2 = 9:

x = [15,9,7,13]         ▲ │ this+2         └─┘  

in third round find ourselves doing not obvious. instead of replacing 7 5+2 replace 9+2 instead because we've replaced 5 9:

x = [15,9,11,13]         │ ▲  this+2 └─┘  

now replace last element 15+2 using same reasoning above:

x = [15,9,11,17]       │       ▲       └───────┘       this+2 

Comments

Popular posts from this blog

javascript - Bootstrap Popover: iOS Safari strange behaviour -

Magento/PHP - Get phones on all members in a customer group -

session - Logging Out Using PHP -